简体   繁体   中英

Efficiently assigning a name to a new variable based on a list of names in r

Suppose I have a list of names new.var.names <- c("a", "b", "c") . And I have a dataframe DF - it doesn't matter what it contains - let's assume this:

StudyID <- c('sid124','sid66537','sid78848')
age <- c(87, 63, 45)
bmi <- c(24.3,19.2,23.5)
data <- data.frame(StudyID, age, bmi)

Now I want to add new variables and base their names on a list, new.var.names . I would do something like:

data$NewVar <- data$bmi/data$age

But I want to make multiple new variables, so naively I would create these like so:

data$a <- data$bmi/data$age
data$b <- data$bmi/data$age
data$c <- data$bmi/data$age

Obviously this is not efficient, as in the real world my list is rather long - hundreds of items. So I'd like to do something like:

for (v in new.var.names){
data$v <- data$bmi/data$age
}

But that wouldn't work - I've tried and somehow I knew it wouldn't hence the post :-P - as it creates the variable v , while I want to create the variables a, b, c . How do I get to that?

Thanks and best,

Sander

I guess you can just do this:

Update: copying and pasting data from question to show it works

StudyID <- c('sid124','sid66537','sid78848')
age <- c(87, 63, 45)
bmi <- c(24.3,19.2,23.5)
data <- data.frame(StudyID, age, bmi)

data$NewVar <- data$bmi/data$age

new.var.names <- c("a", "b", "c")

for (v in new.var.names){
  data[,c(v)] <- data$bmi/data$age
}

I don't see why you want to create three columns with exactly the same data, but you must have a reason for this?

I may have found the answer:

for (v in 1:length(new.var.names)){
  print(new.var.names[v]) # these are just for debugging/sanity check
  data[[ new.var.names[v] ]] <- data$bmi/data$age
  print(table(data[[ new.var.names[v] ]])) # these are just for debugging/sanity check
}

Awesome! Thanks for the help @user3640617

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.

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