简体   繁体   English

如何读取用户输入(字符)作为列名(对象名)

[英]How to read a user input (character) as a column name (object name)

I have a data set like, 我有一个数据集

En     Mn    Hours  var1       var2 
1      1     1      0.1023488  0.6534707 
1      1     2      0.1254325  0.5423215 
1      1     3      0.1523245  0.2542354 
1      2     1      0.1225425  0.2154533 
1      2     2      0.1452354  0.4521255 
1      2     3      0.1853324  0.2545545 
2      1     1      0.1452369  0.2321542 
2      1     2      0.1241241  0.2525212 
2      1     3      0.0542232  0.2626214 
2      2     1      0.8542154  0.2154522 
2      2     2      0.0215420  0.5245125 
2      2     3      0.2541254  0.2542512 

var <- as.character(readline('Enter the variable of your choice')) 

the var stores the user input Ex: var1 var存储用户输入,例如: var1

and if I use it in some R commands say cbind or any for that matter, it doesn't work. 如果我在某些R命令中使用cbind或其他命令,则无法使用。 simple one if a is a dataset a$var doesn't work. 一个简单的如果a是数据集a$var不起作用。 Ex: aggregate(cbind(var)~Mn+hours,a, FUN=mean) 例如: aggregate(cbind(var)~Mn+hours,a, FUN=mean)

And I have a var1 , var2 , var3 like some 30 columns and I want to read multiple inputs from the user 我有一个var1var2var3例如30列,我想从用户那里读取多个输入

like when user is prompted to enter the variable names he enters like var1 var2 var3 (space or comma separated it doesn't matter for me) then I need to read them and use them in the R command line to get some result. 例如,当提示用户输入他输入的变量名时,就像var1 var2 var3 (空格或逗号分隔对我来说无关紧要),那么我需要阅读它们并在R命令行中使用它们以获得一些结果。

Lets say your dataframe is named df...And user entered column name as you said.... 假设您的数据框名为df ...,然后用户按照您输入的名称输入了列名。...

var <- as.character(readline('Enter the variable of your choice')) 

df[var] = 0 #assign actual values here... As var one named column is added

You can run it in loop the same code and create n number of columns... 您可以循环运行相同的代码并创建n个列...

Edit 编辑

Now if you want to use user input for various purpose then following are the case, 现在,如果您想将用户输入用于各种目的,那么以下是这种情况,

  1. When you want to refer column directly with data.frame that will be easy 当您想直接使用data.frame引用列时,这很容易

    df[var]

  2. When you want to refer column in some function or formula then you have to do it like this 当您想在某些函数或公式中引用列时,则必须这样做

    aggregate(cbind(get(var1),get(var2))~Mn+hours,a, FUN=mean)

Concept behind get() is, it will put actual value (column name) in formula for you... get()背后的概念是,它将为您在公式中放入实际值(列名称)...

Updated 更新

Refer this for specially aggregate function : Name columns within aggregate in R 有关特殊的聚合函数,请参见: R中聚合中的名称列

I hope this will work for you... 我希望这对您有用...

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

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