简体   繁体   English

使用转换 dplyr 使用变量的字符串内容来引用数据帧中的列

[英]use string content of a variable to refer to a column in a dataframe using transmute dplyr

I would like to use the variable "second_column" as a variable to refer to the column "test1$b".我想使用变量“second_column”作为引用列“test1$b”的变量。 I tried different things, but couldn't find any solutions yet.我尝试了不同的东西,但还没有找到任何解决方案。 test1 and test2 should be the same in the end... test1 和 test2 最终应该是一样的...

test1 <- data.frame(a = 1:5, b = 6:10)

second_column = "b"

test2 <- test1 %>% 
  transmute(variable1 = a,
         variable2 = second_column
  )

test1
test2

I would suggest using !!我建议使用!! from rlang and as.name() .来自rlangas.name() These two elements are useful for the kind of evaluation you want in order to create your variables:这两个元素对于创建变量所需的评估类型很有用:

#Data
test1 <- data.frame(a = 1:5, b = 6:10)
#Var name
second_column = "b"
#Data 2
test2 <- test1 %>% 
  transmute(variable1 = a,
            variable2 = !!as.name(second_column)
  )
#Dataframes
test1
test2

Output:输出:

test1

  a  b
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10

test2

  variable1 variable2
1         1         6
2         2         7
3         3         8
4         4         9
5         5        10

You can use .data pronoun :您可以使用.data代词:

library(dplyr)

second_column = 'b'
test2 <- test1 %>% 
          transmute(variable1 = a,
                    variable2 = .data[[second_column]])
test2

#  variable1 variable2
#1         1         6
#2         2         7
#3         3         8
#4         4         9
#5         5        10

We can just use base R for this我们可以为此使用base R

data.frame(variable1 = test1[[1]], variable2 = test1[[second_column]])
#   variable1 variable2
#1         1         6
#2         2         7
#3         3         8
#4         4         9
#5         5        10

The operation showed in the OP's post needs only select and select can take both quoted or unquoted OP 的帖子中显示的操作只需要selectselect可以带引号或不带引号

library(dplyr)
test1 %>% 
    select(variable1 = a, variable2 = second_column)
#    variable1 variable2
#1         1         6
#2         2         7
#3         3         8
#4         4         9
#5         5        10

Or using transmute with across或者使用transmute with across

library(stringr)
test1 %>%
    transmute(across(c(a, second_column))) %>%
    rename_with(~ str_c('variable', seq_along(.)))
#  variable1 variable2
#1         1         6
#2         2         7
#3         3         8
#4         4         9
#5         5        10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM