我想使用 for 回圈對資料框串列中的每個元素進行相同的操作。然后我想使用元素的原始名稱來分配這些名稱。我想知道在我只是重新分配相同名稱或使用帶有后綴或前綴的舊名稱分配的情況下如何執行此操作。
我可以通過使用 paste0 添加新名稱來做到這一點,例如:
# load example data frames and add to list
data("iris")
data("cars")
list_df <- list(iris, cars)
# create new list for manipulated data frames. Using head() as an example.
list_head < - list()
# for loop to take head of each data frame in list_df, assign iterative name and add to list_head
for (i in 1:length(list_df){
temp <- head(list_df[[i]])
new_list[[paste0("df_head",i)]] <- temp
}
我希望能夠基于迭代在回圈中分配一個變數,其中分配的名稱與舊名稱相同,和/或舊名稱加上后綴/前綴,例如“cars_head”。添加到串列部分并不重要,但如果這也可以直接完成,那就太好了。
uj5u.com熱心網友回復:
我認為這是一種更像 R 的方法...
data("iris")
data("cars")
library(tibble)
#create a list with names of the elements
list_df <- tibble::lst(iris, cars)
#get head of list's elements
new_list <- lapply(list_df, head)
#new names
names(new_list) <- paste0(names(list_df), "_head")
new_list
# $iris_head
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
#
# $cars_head
# speed dist
# 1 4 2
# 2 4 10
# 3 7 4
# 4 7 22
# 5 8 16
# 6 9 10
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452821.html
上一篇:如何遍歷資料集比較相鄰的行并在新列中輸出結果的關系?
下一篇:python中的字謎演算法
