【问题标题】:"Evaluation error: object not found" in dplyr when calling an object not created yet调用尚未创建的对象时,dplyr 中的“评估错误:找不到对象”
【发布时间】:2019-03-05 06:02:03
【问题描述】:

我有与此类似的代码,使用管道创建数据帧“full_tb”,但由于倒数第二行(产生 ID 列的变异)正在调用尚未创建的对象(“full_tb”)而失败还没有。

library(random)
library(dplyr)  

set.seed(1)
Codes <- as.vector(randomStrings(n = 10, len = 3, digits = TRUE, upperalpha = FALSE,
         unique = TRUE))

frame1 <- data.frame(
  A = sort(Codes),
  B = sample(x = c("Tree", "Shrub", "Fern"), size = 10, replace = TRUE))
)

frame2 <- data.frame(
  Row_no = sort(sample(x = 1:10)),
  C = sample(x = sample(x = c("Tree", "Shrub", "Fern"), size = 30, replace = TRUE))
)

# Here is where the problem begins

full_tb <- frame1 %>% mutate(Row_no = as.numeric(rownames(frame1))) %>%  
           inner_join(frame2) %>%  
           mutate(ID = as.numeric(rownames(full_tb))) %>%  
           select(ID, A, B, C)

# Joining by = "Row_no"  
# Error in mutate_impl(.data, dots):   
# Evaluation error: object 'full_tb' not found   

但是,如果我将管道分成两块,它运行正常。

full_tb <- frame1 %>% mutate(Row_no = as.numeric(rownames(frame1))) %>%  
           inner_join(frame2)

# Joining by = "Row_no"  

full_tb  <- full_tb %>% mutate(ID = as.numeric(rownames(full_tb))) %>%  
            select(ID, A, B, C)

是否有一种解决方法可以将所有内容通过管道传输到一个块中,而不必将第一个代码块分成两部分?

【问题讨论】:

标签: r dplyr


【解决方案1】:

通过在我们想要管道的代码块中添加一个点作为行名的参数,在连接之后为整个数据帧生成 ID。因此,无需在 rownames 中指定数据框的名称。

full_tb <- frame1 %>% mutate(Row_no = as.numeric(rownames(frame1))) %>%  
           inner_join(frame2) %>%  
           mutate(ID = as.numeric(rownames(.))) %>%  
           select(ID, A, B, C)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多