来自Python + Pandas,我试图在R data.frame中转换列。
在Python /熊猫中,我会这样做:df[['weight']] = df[['weight']] / 1000
在R中,我想到了这个:
convertWeight <- function(w) {
return(w/1000)
}
df$weight <- lapply(df$weight, convertWeight)
我知道具有功能dplyr
的库mutate
。那也可以让我转换列。
在不使用dplyr
库的情况下,是否有其他方法可以改变列?接近Pandas
的方式吗?
编辑
检查df $ weight中的值,我看到了:
> 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"
这既不是数字,也不是字符。为什么列出?
顺便说一句:我像这样从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的知识。
答案 0 :(得分:1)
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)