简体   繁体   English

使用对数据框中的行进行迭代的函数将元素追加到列表中

[英]Append elements to list using a function that iterates over rows in a data frame

I'm trying to use a list like a python dict, which can be appended to every time a function is run. 我正在尝试使用类似python dict的列表,该列表可以在每次运行函数时附加到列表中。 Ultimately I want to apply the function to every row in a data frame. 最终,我想将该函数应用于数据框中的每一行。 I'm trying it out on some toy data: 我正在尝试一些玩具数据:

foo <- vector(mode="list", length=2)
names(foo) <- c("Larry", "Bob")

myfun <- function(name, round, foo){
 foo[[name]] <<- c(foo[[name]], round)
}

This works when I run it separately over some data: 当我分别对某些数据运行它时,此方法有效:

myfun("Larry", "R2", foo)
myfun("Larry", "R2", foo)
myfun("Bob", "R1", foo)
myfun("Larry", "R1", foo)

foo
$Larry
[1] "R2" "R2" "R1"

$Bob
[1] "R1"

But I can't get the function to work over a data frame: 但是我无法使该功能在数据框架上运行:

datf <- data.frame(name = c("Larry", "Larry", "Bob", "Larry"),
                   round = c("R2", "R2", "R2", "R1"))
mapply(myfun, name=datf$name, round=datf$round, foo=foo)

This produces the following in the console (I'm not sure why?): 这会在控制台中产生以下内容(我不确定为什么吗?):

[1] 1 1 2 3

and the following in foo: 以及foo中的以下内容:

foo
$Larry
[1] 2

$Bob
[1] 3

My other thought was to try applying myfun() in a for loop: 我的另一个想法是尝试在for循环中应用myfun():

for(row in 1:nrow(datf)){
  myfun(datf$name, datf$round, foo)
}

But this produces an error: 但这会产生一个错误:

Error in foo[[name]] : no such index at level 2

Any insights would be appreciated! 任何见解将不胜感激!

A little better example of the function you're trying to run and the result would be helpful. 您尝试运行的函数的一个更好的示例,其结果会有所帮助。 I would think about using the dplyr::mutate function. 我会考虑使用dplyr :: mutate函数。 Alternatively, if you're trying to just do something simple, I think you can just make a new column in the dataframe datf$new <- myfun(inputs) 另外,如果您只是想做一些简单的事情,我想您可以在数据datf$new <- myfun(inputs)一个新列datf$new <- myfun(inputs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM