Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

dataframe - Change the rownames of each dataset in a loop in R

I am trying to change the index of my database. They have the same name, what changes is their number (dataset_id_1, dataset_id_2, ...., dataset_id_76). The datasets are in dataframe format and have 8 columns each.

I would like to change the current index of each (288 rows) into 740 to 1027.

I tried the following with no success:

range = c(740:1027)
    
for (i in 1:76) {
  rownames(dataset_id_[[i]]) = range
}

Do you know how to solve the problem?

question from:https://stackoverflow.com/questions/65671981/change-the-rownames-of-each-dataset-in-a-loop-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following should work:

new_index <- 740:1027

for (i in 1:76) { 
   temp <- get(paste0('dataset_id_',i))
   rownames(temp) <- new_index
   assign(paste0('dataset_id_',i),temp)
}

You can get the name of each dataset through paste0('data_set_id_',i), and then the get command allows you to access the actual dataframe from character name of the dataset. This object has its rownames modified, then the assign command re-assigns this new object to the original name.

However, there may be a more natural way to carry out the operation you want at the stage where you create each of these dataframes from the larger one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...