在R中轻松地将值插入数据帧

  • 本文关键字:插入 数据帧 r matching
  • 更新时间 :
  • 英文 :


考虑以下数据帧:

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。但是我该怎么做呢?我应该可以同时改变多个细胞(例如"农业"one_answers"渔业"(。

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

最新更新