【问题标题】:In R dplyr, why there is a single quote after spread function?在 R dplyr 中,为什么传播函数后有一个单引号?
【发布时间】:2019-06-04 10:07:53
【问题描述】:

我正在尝试使用 dplyr 展开函数将一列展开为多列。一旦传播,对列的访问就会有一个单引号,我想删除它,因为它妨碍了我过滤数据框

以下是我的代码

# Create Test Frame
testframe = data.frame(name = c("foo-tt.0","bar-tt.0","dd-tt.0","tt-tt.0"),age=as.numeric(c(40,38,10,8)))
#Pivot using name
testframe_pivot <- testframe %>% spread(name,age)

我需要像下面这样访问框架

testframe_pivot$`bar-tt.0` ## I don't want these quotes
[1] 38

为什么我不能得到喜欢(预期输出)

> testframe_pivot$bar-tt.0
[1] 38

我得到了

> testframe_pivot$bar-tt.0
Error: object 'tt.0' not found

我知道这是因为字母和其他字符的混合,但不知道如何摆脱这个错误

后果是……

>name_I_want = c("foo-tt.0")

>select_(testframe_pivot,.dot=name_I_want)
Error in .f(.x[[i]], ...) : object 'foo' not found

【问题讨论】:

  • dplyr::select(testframe_pivot, name_I_want) 似乎有效?

标签: r dplyr spread


【解决方案1】:

名称的问题在于- 符号。除非您摆脱它,否则您将无法在没有反引号的情况下使用 $ 运算符。 base-R 有两个选项:

要么将名称更正为 R 语法上正确的名称。make.names 效果很好:

names(testframe_pivot) <- make.names(names(testframe_pivot))
testframe_pivot
#  bar.tt.0 dd.tt.0 foo.tt.0 tt.tt.0
#1       38      10       40       8

或者您使用 [[ 和字符串作为子集:

testframe_pivot[['bar-tt.0']]
#[1] 38

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多