Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.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 - Fatal编程技术网

R动态重命名列并忽略缺少的列

R动态重命名列并忽略缺少的列,r,R,我有一个需要动态重命名特定列的数据集 例如,我通常会按以下方式重命名“mtcars”数据集: # THIS WORKS # Load data data <- mtcars # Gather data.frame with columns to rename, I am doing it this way because I generally have # a long list of "configurations" to plot that I go

我有一个需要动态重命名特定列的数据集

例如,我通常会按以下方式重命名“mtcars”数据集:

# THIS WORKS    
# Load data
data <- mtcars

# Gather data.frame with columns to rename, I am doing it this way because I generally have 
# a long list of "configurations" to plot that I go through in a for loop.  Might not be the most 
# efficient, but it generally works for me.
Columns_to_rename <- data.table(X = "mpg", Y = "gear", Color = "carb")

# Rename columns
plot_data <- data %>%
    dplyr::rename(X := !!Columns_to_rename$X[1],
                  Y := !!Columns_to_rename$Y[1],
                  Color := !!Columns_to_rename$Color[1]) %>%
    dplyr::select(X, Y, Color)
据我所知,
dplyr
包要求所有列都存在。坚持使用
tidyverse
,我研究了使用
plyr
包,因为我知道这会导致缺少列名。不幸的是,我不知道如何动态调用这些列。我已经查看了以前的StackOverflow问题和答案,但没有看到有人需要在重命名时将这两个原则结合起来


谢谢

一个选项是在%

library(dplyr)
nm1 <- unlist(Columns_to_rename)
nm2 <-  nm1[nm1 %in% names(data)]
data %>% 
      rename(!!! nm2) %>%
      select(names(nm2)) %>%
      head

或者另一个选项是
rename_at
rename_with
在子集向量('nm2')上

注意:我们也可以在“nm1”上使用
任意
,但问题是
名称(nm1)
的长度不匹配

data %>% 
      rename_at(vars(any_of(nm1)), ~ names(nm2))

我知道一般情况下最好避免这种情况,但在这种情况下,您可以根据未命名列的位置来调用它们吗?这不起作用,因为我的“columns\u to\u rename”在每次迭代之间都会更改,因此列号会随每次迭代而更改。但是谢谢你的主意!
#                    X Y
#Mazda RX4         21.0 4
#Mazda RX4 Wag     21.0 4
#Datsun 710        22.8 4
#Hornet 4 Drive    21.4 3
#Hornet Sportabout 18.7 3
#Valiant           18.1 3
data %>%
    rename_at(vars(all_of(nm2)), ~ names(nm2)) %>%
    select(names(nm2)) %>%
    head
data %>% 
      rename_at(vars(any_of(nm1)), ~ names(nm2))