将列字符串转换为 r 数据框中的数字

将列字符串转换为 r 数据框中的数字

问题描述:

我有一个包含一列字符串的数据框,如下所示:

I have a dataframe that has a column of strings as follows:

    mydata <- c("-1.356670,35.355030",
            "-1.356670,35.355030", 
            "-1.356620,35.355890", 
            "-1.356930,35.358660", 
            "-1.357000,35.359060"
    )

    df <- data.frame(mydata)

我想将其转换为包含两列longlat"的数据框,每列都是数字类型.最好的方法是什么?我已尝试使用 lapply,但似乎无法使其工作.

I want to convert it into a dataframe containing two columns" long and lat, with each being a numeric type. What is the best way to do this? I've tried using lapply, but cannot seem to make it work.

使用基础 R,您可以:

With base R you can do:

df$Long <- as.numeric(sapply(strsplit(as.character(df$mydata), ","), function(x) x[1]))
df$Lat <- as.numeric(sapply(strsplit(as.character(df$mydata), ","), function(x) x[2]))

               mydata     Long      Lat
1 -1.356670,35.355030 -1.35667 35.35503
2 -1.356670,35.355030 -1.35667 35.35503
3 -1.356620,35.355890 -1.35662 35.35589
4 -1.356930,35.358660 -1.35693 35.35866
5 -1.357000,35.359060 -1.35700 35.35906

或者使用来自 data.tabletstrsplit():

Or with tstrsplit() from data.table:

df$Long <- as.numeric(tstrsplit(df$mydata, ",")[[1]])
df$Lat <- as.numeric(tstrsplit(df$mydata, ",")[[2]])

还有@clmarquart 提出的来自 data.tabletstrsplit():

Also with tstrsplit() from data.table as proposed by @clmarquart:

setDT(df)[, c("lat", "long") := tstrsplit(mydata, ",", fixed = TRUE)]