[英]Recalculate a column in data.frame
來自Python + Pandas,我嘗試轉換R data.frame中的列。
在Python / Pandas中,我會這樣做: df[['weight']] = df[['weight']] / 1000
在RI中提出了以下內容:
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有很多了解。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.