在 R 中轻松地将值插入数据框
Insert value into dataframe easily in R
考虑以下 data.frame:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(0,0,0))
我想轻松地将一个值放入数据框中。假设我想要“农业”的数字 1。当然,在这种情况下,我可以很容易地做到这一点:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(1,0,0))
但是我有一个巨大的数据框,所以做起来并不容易。相反,我可以写:
change <- c("Agriculture", 1)
然后如果是macthing,那么它会更新df。但是我该怎么做呢?我应该可以同时更改多个单元格(例如,“农业”和“渔业”)。
一个dplyr
解决方案:
您可以写下要更新的行业列表,然后在 mutate
函数中使用 %in%
运算符:
library(dplyr)
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(0,0,0))
list_of_industries <- c("Agriculture","Fishery")
df <- df %>%
mutate(Value = ifelse(Industry %in% list_of_industries,
1,
0))
输出:
Industry Value
1 Agriculture 1
2 Fishery 1
3 Industry 0
你可以试试
df$Value[df$Industry == "Agriculture"] <- 1
Industry Value
1 Agriculture 1
2 Fishery 0
3 Industry 0
和
df$Value[df$Industry %in% c("Agriculture", "Fishery")] <- 1
Industry Value
1 Agriculture 1
2 Fishery 1
3 Industry 0
使用合并和就地更新 data.table
方法
library(data.table)
# set df as dt
dt <- data.table(df)
# update table
updt <- fread(text="
Industry,New_Value
Agriculture,1
Fishery,2
")
# temporary merge on Industry column to fetch new value
# and inplace update dt
dt[
updt, on="Industry", # merging
Value := New_Value # inplace update
]
得到
Industry Value
1: Agriculture 1
2: Fishery 2
3: Industry 0
考虑以下 data.frame:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(0,0,0))
我想轻松地将一个值放入数据框中。假设我想要“农业”的数字 1。当然,在这种情况下,我可以很容易地做到这一点:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(1,0,0))
但是我有一个巨大的数据框,所以做起来并不容易。相反,我可以写:
change <- c("Agriculture", 1)
然后如果是macthing,那么它会更新df。但是我该怎么做呢?我应该可以同时更改多个单元格(例如,“农业”和“渔业”)。
一个dplyr
解决方案:
您可以写下要更新的行业列表,然后在 mutate
函数中使用 %in%
运算符:
library(dplyr)
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(0,0,0))
list_of_industries <- c("Agriculture","Fishery")
df <- df %>%
mutate(Value = ifelse(Industry %in% list_of_industries,
1,
0))
输出:
Industry Value
1 Agriculture 1
2 Fishery 1
3 Industry 0
你可以试试
df$Value[df$Industry == "Agriculture"] <- 1
Industry Value
1 Agriculture 1
2 Fishery 0
3 Industry 0
和
df$Value[df$Industry %in% c("Agriculture", "Fishery")] <- 1
Industry Value
1 Agriculture 1
2 Fishery 1
3 Industry 0
使用合并和就地更新 data.table
方法
library(data.table)
# set df as dt
dt <- data.table(df)
# update table
updt <- fread(text="
Industry,New_Value
Agriculture,1
Fishery,2
")
# temporary merge on Industry column to fetch new value
# and inplace update dt
dt[
updt, on="Industry", # merging
Value := New_Value # inplace update
]
得到
Industry Value
1: Agriculture 1
2: Fishery 2
3: Industry 0