R - 为什么在另一个数据框中搜索值时在此数据框中应用 return 列表?

R - Why does sapply return lists within this dataframe when searching for values in another dataframe?

我有以下两个2 data.frames:

df1

structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1, 
1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305, 
4455134, 4398594), post_id_unique = c("1-NA", "1-post-1", "2-NA", 
"2-post-2", "2-post-2", "2-post-2"), to = list(NULL, 1L, NULL, 
    2L, 2L, 2L)), .Names = c("thread_id", "course_week", "user_id", 
"post_id_unique", "to"), row.names = c(NA, 6L), class = "data.frame")

df2

structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1, 
1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305, 
4455134, 4398594), post_id_unique = c("1-post-1", "1-post-1125", 
"2-post-2", "2-post-3", "2-post-43", "2-post-54")), .Names = c("thread_id", 
"course_week", "user_id", "post_id_unique"), row.names = c(NA, 
6L), class = "data.frame")

我正在尝试将 df1$to 替换为 df2$user_id 中匹配 $post_id_unique 两个文件中的列。

我为此编写了以下代码:

from <- as.list(df1$post_id_unique)
replace <- function(i){if(grepl("NA",i)!=TRUE) {df2[df2$post_id_unique==i,1]}}
df1$to <- sapply(from, replace)

这几乎完美地工作...除了 df1$to 中的每个值都是列表而不是数字或字符向量:

'data.frame':   6 obs. of  5 variables:
 $ thread_id     : int  1 1 2 2 2 2
 $ course_week   : num  1 1 1 1 1 1
 $ user_id       : num  1237305 3001241 1237305 1237305 4455134 ...
 $ post_id_unique: chr  "1-NA" "1-post-1" "2-NA" "2-post-2" ...
 $ to            :List of 6
  ..$ : NULL
  ..$ : int 1
  ..$ : NULL
  ..$ : int 2
  ..$ : int 2
  ..$ : int 2

为什么我的原始代码在数据框中创建列表?我怎样才能取消列出它们?或者避免以它们开头。

我知道这类似于 merge(),但出于学习和其他原因,我对以这种方式进行操作很感兴趣。

"problem" 是有时您的 replace() 函数没有 return 值(当 i 值包含 "NA" 时)。由于 sapply 总是 returns 一个与输入长度相同的对象,因此函数的 NULL 值是 returned。 NULL 不能放在简单向量中,因此 sapply 的结果被转换为列表。你可以通过 return 一个 NA 而不是什么都不做来解决这个问题

replace <- function(i){if(grepl("NA",i)!=TRUE) {df2[df2$post_id_unique==i,1]} else {NA}}

但实际上您似乎在进行基本的左合并操作。基本语法是

merge(df1, df2, by="post_id_unique", all.x=T)