首页 > 解决方案 > 如何在R中的“data $”之后动态分配变量名

问题描述

我想分配一个变量“dv1”,它将给定变量名称传递到公式中,以便我可以创建动态数据引用。

代码

# Define terms
esto1<-g6e ### temporarily stored variable #1
esto2<-g6c ### temporarily stored variable #2, etc. 
dv1<-"attitude"     ### The dependent variable that you'll be testing
# 
shapiro.test(esto1$dv1)
shapiro.test(esto2$dv1)

# Given esto1=g6e, esto2=g6c, and dv1=attitude, the statements above should be the equivalent of: 
shapiro.test(g6e$attitude)
shapiro.test(g6c$attitude)

标签: r

解决方案


以下代码似乎有效:

  # Define terms
esto1<-g6e ### temporarily stored variable #1
esto2<-g6c ### temporarily stored variable #2, etc. 
dv1<-"attitude"     ### The dependent variable that you'll be testing

# attempt 2
shapiro.test(esto1[[dv1]])
shapiro.test(esto2[[dv1]])

# Given esto1=g6e, esto2=g6c, and dv1=attitude, the statements above should be the equivalent of: 
shapiro.test(g6e$attitude)
shapiro.test(g6c$attitude)

我使用 $ 和列名向量从动态选择数据框列中推断出 这一点。


推荐阅读