我有一個包含 142個資料框file_content的串列和一個來自id_list <- list(as.character(1:length(file_content)))
我正在嘗試向中的period每個資料框添加一個新列file_content。
所有資料框都與2021-03-16下面類似。
`2021-03-16` <- file_content[[1]] # take a look at 1/142 dataframes in file_content
head(`2021-03-16`)
author_id created_at id tweet
1 3.304380e 09 2018-12-01 22:58:55 00:00 1.069003e 18 @Acosta I hope he didna€?t really say a€?mucka€\u009d.
2 5.291559e 08 2018-12-01 22:57:31 00:00 1.069003e 18 @Acosta I like Mattis, but why does he only speak this way when Individual-1 isn't around?
3 2.195313e 09 2018-12-01 22:56:41 00:00 1.069002e 18 @Acosta What did Mattis say about the informal conversation between Trump and Putin at the G20?
4 3.704188e 07 2018-12-01 22:56:41 00:00 1.069002e 18 @Acosta Good! Tree huggers be damned!
5 1.068995e 18 2018-12-01 22:56:11 00:00 1.069002e 18 @Acosta @NinerMBA_01
6 9.983321e 17 2018-12-01 22:55:13 00:00 1.069002e 18 @Acosta Really?
我嘗試period使用以下代碼添加列,但它將所有 142 個值添加id_list到file_content.
for (id in length(id_list)) {
file_content <- lapply(file_content, function(x) { x$period <- paste(id_list[id], sep = "_"); x })
}
uj5u.com熱心網友回復:
你很接近,錯誤是你需要在id_list[[id]].
for (id in length(id_list)) {
file_content <- lapply(file_content, function(x) {
x$period <- paste(id_list[[id]], sep = "_")
x
})
}
# $`1`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
#
# $`2`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
#
# $`3`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
您也可以嘗試Map()保存幾行。
Map(`[<-`, file_content, 'period', value=id_list)
# $`1`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
#
# $`2`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
#
# $`3`
# X1 X2 X3 X4 period
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
資料:
file_content <- replicate(3, data.frame(matrix(1:12, 3, 4)), simplify=F) |> setNames(1:3)
id_list <- list(as.character(1:length(file_content)))
uj5u.com熱心網友回復:
我們可能會使用imap
library(purrr)
library(dplyr)
imap(file_content, ~ .x %>%
mutate(period = .y))
或Map從base R
Map(cbind, file_content, period = names(file_content))
在 OP 的代碼中,通過ie包裝將id_list其創建為元素single listlist
list(1:5)
對比
as.list(1:5)
在這里,我們不需要轉換list為向量就足夠了
id_list <- seq_along(file_content)
此外,for回圈在單個元素上回圈,即最后一個元素length
for (id in length(id_list)) {
^^
相反,它會是1:length. 此外,賦值應該在單個串列元素file_content[[id]]上,而不是整個list
for(id in seq_along(id_list)) {
file_content[[id]]$period <- id_list[id]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426677.html
下一篇:每列R中特定值的次數
