如何使用组合名称重命名r中的变量

时间:2022-08-07 10:47:23

I can make this code:

我可以制作这段代码:

#set seed
set.seed(848)

#make variables (similar, not same)
myvar_a <- rnorm(n = 100, mean = 1, sd = 2)
myvar_b <- rnorm(n = 100, mean = 2, sd = sqrt(3))
myvar_c <- rnorm(n = 100, mean = 4, sd = sqrt(5))
myvar_d <- rnorm(n = 100, mean = 8, sd = sqrt(8))

#transform variables
for(i in 1:4){
     if(i ==1){
          myvar_1 <- myvar_a
     } else if (i==2) {
          myvar_2 <- myvar_b
     } else if (i==3) {
          myvar_3 <- myvar_b
     }  else {
          myvar_4 <- myvar_b
     } 
}

It gives me this:

它给了我这个:

如何使用组合名称重命名r中的变量

Is there a way to do it with "paste" and the loop variable?

有没有办法用“粘贴”和循环变量来做到这一点?

In MATLAB there is the eval that treats a constructed character string as a line of code, so I could create sentences then run them from within the code.

在MATLAB中有一个eval,它将构造的字符串视为一行代码,因此我可以创建句子,然后在代码中运行它们。

2 个解决方案

#1


1  

l <- list()

#transform variables
for(i in 1:4){
  if(i ==1){
    l[[paste0("myvar_", i)]] <- myvar_a
  } else if (i==2) {
    l[[paste0("myvar_", i)]] <- myvar_b
  } else if (i==3) {
    l[[paste0("myvar_", i)]] <- myvar_b
  }  else {
    l[[paste0("myvar_", i)]] <- myvar_b
  } 
}

print(l)

Of course, an experienced R user would use lapply instead of the for loop.

当然,有经验的R用户会使用lapply而不是for循环。

#2


1  

You can do:

你可以做:

for(i in 1:4){
  let <- if(i == 1) "a" else "b"
  assign(paste0("myvar_", i), get(paste0("myvar_", letters[i])))
}

But as others say, this is not really recommendable.

但正如其他人所说,这不是真正值得推荐的。

#1


1  

l <- list()

#transform variables
for(i in 1:4){
  if(i ==1){
    l[[paste0("myvar_", i)]] <- myvar_a
  } else if (i==2) {
    l[[paste0("myvar_", i)]] <- myvar_b
  } else if (i==3) {
    l[[paste0("myvar_", i)]] <- myvar_b
  }  else {
    l[[paste0("myvar_", i)]] <- myvar_b
  } 
}

print(l)

Of course, an experienced R user would use lapply instead of the for loop.

当然,有经验的R用户会使用lapply而不是for循环。

#2


1  

You can do:

你可以做:

for(i in 1:4){
  let <- if(i == 1) "a" else "b"
  assign(paste0("myvar_", i), get(paste0("myvar_", letters[i])))
}

But as others say, this is not really recommendable.

但正如其他人所说,这不是真正值得推荐的。