R 如何在函数中使用字符串作为变量名?

R 如何在函数中使用字符串作为变量名?,r,R,我正在分析一项调查中的问题,每个回答都被分为三类中的一类。示例数据为: library(tidyverse) Do.You.Live.in.the.USA <- as.factor(c("Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes")) Whats.your.favorite.color <- as.factor(c("Red", "Blue", "Green", "Red", "Blue", "Green", "

我正在分析一项调查中的问题,每个回答都被分为三类中的一类。示例数据为:

library(tidyverse)

Do.You.Live.in.the.USA <- as.factor(c("Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes"))
Whats.your.favorite.color <- as.factor(c("Red", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Blue"))
Cluster <- c(1,2,3,3,2,1,3,2,1)

survey_data <- data.frame(Do.You.Live.in.the.USA, Whats.your.favorite.color, Cluster)
survey_data[] <- lapply(survey_data, factor)
库(tidyverse)

Do.You.Live.in.the.USA这里有一个直接的方法:

clust_sum_fun <- function(x)
  cbind(summary(cluster_1_df[, x]), summary(cluster_2_df[, x]), summary(cluster_3_df[, x]))  
(US_live_summary <- clust_sum_fun("Do.You.Live.in.the.USA"))
#     [,1] [,2] [,3]
# No     1    2    1
# Yes    2    1    2

clust\u sum\u fun如果不能对字符串使用
$
,请改用
[
cluster_1  <- summary(cluster_1_df$Do.You.Live.in.the.USA)
cluster_2  <- summary(cluster_2_df$Do.You.Live.in.the.USA)
cluster_3  <- summary(cluster_3_df$Do.You.Live.in.the.USA)
US_live_summary <- cbind(cluster_1, cluster_2, cluster_3)
clust_sum_fun <- function(x){
  cbind(summary(cluster_1_df$x), summary(cluster_2_df$x),  summary(cluster_3_df$x))
}

US_live_summary <- clust_sum_fun(Do.You.Live.in.the.USA)
clust_sum_fun <- function(x)
  cbind(summary(cluster_1_df[, x]), summary(cluster_2_df[, x]), summary(cluster_3_df[, x]))  
(US_live_summary <- clust_sum_fun("Do.You.Live.in.the.USA"))
#     [,1] [,2] [,3]
# No     1    2    1
# Yes    2    1    2