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
and if I use it in some R commands say cbind
or any for that matter, it doesn't work. simple one if a
is a dataset a$var
doesn't work. Ex: 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
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.
Lets say your dataframe is named df...And user entered column name as you said....
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...
Edit
Now if you want to use user input for various purpose then following are the case,
When you want to refer column directly with data.frame that will be easy
df[var]
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...
Updated
Refer this for specially aggregate function : Name columns within aggregate in R
I hope this will work for you...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.