来自python pandas,我尝试转换r data.frame中的列。
在python/pandas中,我会这样做: df[['weight']] = df[['weight']] / 1000
在r中,我想到了:
convertWeight <- function(w) {
return(w/1000)
}
df$weight <- lapply(df$weight, convertWeight)
我知道具有函数mutate
的库dplyr
。那也可以使我转换列。
在不使用dplyr
库的情况下,有其他方法可以突变列吗?与Pandas
这样做的事情?
编辑
检查df $重量中的值我看到了:
> df[1,]
date weight
1 1.552954e+12 84500.01
> typeof(df[1,1])
[1] "list"
> df$weight[1]
[[1]]
[1] 84500.01
> typeof(df$weight[1])
[1] "list"
这既不是数字,也不是字符。为什么列出?
btw:我有类似JSON导入的数据:
library(rjson)
data <- fromJSON(file = "~/Desktop/weight.json")
# convert json data to data.frame
df <- as.data.frame(do.call("rbind", json_data))
# select only two columns
df <- df[c("date", "weight")]
# now I converted the `date` value from posix to date
# and the weight value from milli grams to kg
# ...
显然我有很多了解R。
df$weight = as.numeric(df$weight)
df$weight = df$weight / 1000
# If you would like to eliminate the display of scientific notation:
options(scipen = 999)
# If having difficulty still because of the list, try
df = as.data.frame(df)