Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法将变量名动态添加到R中的数据帧_R_Tidyverse - Fatal编程技术网

无法将变量名动态添加到R中的数据帧

无法将变量名动态添加到R中的数据帧,r,tidyverse,R,Tidyverse,我希望基于另一个数据帧,将一组变量附加到现有的数据帧上。我用这个来为自己做准备,但实际上什么都没做 假设在下面的代码中,我有一个名为comp的数据框,我想通过迭代遍历comp中的每一列,并通过列“vs”中的第二行来命名该变量,从而将空变量添加到数据框iris: library(tidyverse) comp <- as_tibble(combn(letters[1:4], 2)) mydf <- as_tibble(iris) # Creating a function that

我希望基于另一个数据帧,将一组变量附加到现有的数据帧上。我用这个来为自己做准备,但实际上什么都没做

假设在下面的代码中,我有一个名为
comp
的数据框,我想通过迭代遍历
comp
中的每一列,并通过列“vs”中的第二行来命名该变量,从而将空变量添加到数据框
iris

library(tidyverse)
comp <- as_tibble(combn(letters[1:4], 2))
mydf <- as_tibble(iris)

# Creating a function that creates a variable name for each column in comp
# and creates a variable with that name in df
varname_assign <- function(df, n){
varname <- paste0(comp[[1,n]], "Vs", comp[[2,n]])
mutate_(df, .dots= setNames(list(NA), varname))
return(df)
}

for (i in seq_along(comp)) {
mydf <- varname_assign(mydf, i)
}

mydf

# A tibble: 150 × 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
      <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
1      5.1         3.5          1.4         0.2  setosa

#Nothing happened :(
库(tidyverse)

comp您没有分配
mutate\uu
的返回值。您的
mutate\u
调用没有将结果分配给任何对象,因此它创建了新变量,然后它们就消失了,然后告诉函数显式返回原始的
df
。如果你做了
df显然,我需要更多的咖啡才能发布糟糕的问题。你永远不会喝更多的咖啡出错。你没有分配
mutate\uu
的返回值。你的
mutate\u
调用没有分配任何结果,所以它创建了新的变量,然后它们就消失了,然后告诉函数显式返回原始的
df
。如果你做了
df显然,我需要更多的咖啡才能发布糟糕的问题。你再多喝咖啡也不会出错。
# A tibble: 150 × 11
Sepal.Length Sepal.Width Petal.Length Petal.Width Species  AvsB  AvsC  AvsD  BvsC  BvsD  CvsD
      <dbl>       <dbl>        <dbl>       <dbl>  <fctr>  <lgl> <lgl> <lgl> <lgl> <lgl> <lgl>
1      5.1         3.5          1.4         0.2  setosa    NA    NA    NA    NA    NA    NA