我只有一排小标题:
library('tibble')
df <- tibble(date=2019,
first_col=20,
second_col=30,
third_col=40)
我将密钥作为字符串,例如:
key <- 'first'
现在我可以使用表达式从标题中获取第一个单元格的值:
eval(parse(text=paste0('df$',key,'_col')))
# 20
但是我无法重写此单元格:
eval(parse(text=paste0('df$',key,'_col'))) <- 40
#Error in eval(parse(text = paste0("df$", target, "_col"))) <- 40 :
target of assignment expands to non-language object
答案 0 :(得分:0)
一种方法是使用!!
评估列名,使用:=
分配值
library(dplyr)
df %>% mutate(!!paste0(key,"_col") := 40)
# date first_col second_col third_col
# <dbl> <dbl> <dbl> <dbl>
#1 2019 40 30 40
答案 1 :(得分:0)
我们可以使用
library(dplyr)
library(stringr)
df %>%
mutate(!! str_c(key, "_col") := 40)