将列字符串转换为 r 数据框中的数字 [英] Converting a column string to numeric in an r data frame

查看:45
本文介绍了将列字符串转换为 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)]

这篇关于将列字符串转换为 r 数据框中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆