gpt4 book ai didi

Select column from dataframe using dplyr(使用dplyr从数据帧中选择列)

转载 作者:bug小助手 更新时间:2023-10-28 21:32:05 26 4
gpt4 key购买 nike



I have following code

我有以下代码


library(dplyr)
select_one_col = 'B'
data.frame('A' = 1:3, 'B' = 1:3) %>%
select(A, select_one_col)

I am basically selecting a set of columns where some column names are held in different variable.

我基本上选择了一组列,其中一些列名保存在不同的变量中。


Is there any way to correct above code maintaining the basic style?

有没有什么方法可以在保持基本风格的情况下纠正上述代码?


Thanks for your help

谢谢你的帮忙


更多回答

you could also put select one in two sets of curly brackets ({{select_one_col}})

您还可以将SELECT ONE放在两组大括号中({{SELECT_ONE_COOL}})

优秀答案推荐


The recommended way to do this currently is:

目前,建议使用的方法是:


library(dplyr)

select_one_col = 'B'

data.frame('A' = 1:3, 'B' = 1:3) %>%
select(A, all_of(select_one_col))
#> A B
#> 1 1 1
#> 2 2 2
#> 3 3 3

Created on 2023-09-09 with reprex v2.0.2

创建于2023-09-09,Reprex v2.0.2



Using base::subset

使用base::subset


select_one_col <- 'B'

data.frame(A=1:3, B=1:3) |> subset(select=c('A', select_one_col))
# A B
# 1 1 1
# 2 2 2
# 3 3 3

Note, that 'A'is defined as character in select= argument.

注意,'A'在select= argument中被定义为字符。


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com