R中使用for循环的多个 Dataframe 上的行名

c9qzyr3d  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(175)

我有几个 Dataframe 。我希望第一列是每一行的名称。
我可以这样做1 dataframe:

# Rename the row according the value in the 1st column
row.names(df1) <- df1[,1]

# Remove the 1st column
df1 <- df1[,-1]

但是我想在几个 Dataframe 上这样做。我尝试了几种策略,包括assign和一些get,但都没有成功。这里有两种主要的方法我尝试过:

# Getting a list of all my dataframes
my_df <- list.files(path="data")

# 1st strategy, adapting what works for 1 dataframe
for (i in 1:length(files_names)) {
  rownames(get(my_df[i])) <- get(my_df[[i]])[,1] # The problem seems to be in this line
  my_df[i] <- my_df[i][,-1]
}

# The error is  Could not find function 'get>-'

# 2nd strategy using assign()
for (i in 1:length(my_df)) {
  assign(rownames(get(my_df[[i]])), get(my_df[[i]])[,1]) # The problem seems to be in this line
  my_df[i] <- my_df[i][,-1]
}

# The error is : Error in assign(rownames(my_df[i]), get(my_df[[i]])[, 1]) : first argument incorrect

我真的不知道我错过了什么。当我输入get(my_df[i])get(my_df[[i]])[,1]时,它在控制台中单独工作...
非常感谢那些可以帮助我的人:)

kx1ctssn

kx1ctssn1#

你可以在函数中编写代码,读取数据并将每个 Dataframe 传递给函数。

change_rownames <- function(df1) {
  row.names(df1) <- df1[,1]
  df1 <- df1[,-1]
  df1  
}

my_df <- list.files(path="data")

list_data <- lapply(my_df, function(x) change_rownames(read.csv(x)))
pw136qt2

pw136qt22#

我们可以使用像lapplypurrr::map这样的循环函数来循环所有的 Dataframe ,然后使用dplyr::column_to_rownames,这大大简化了过程。不需要显式的for循环。

library(purrr)
library(dplyr)

map(my_df, ~ .x %>% read.csv() %>% column_to_rownames(var = names(.)[1]))

相关问题