将列(dplyr tbl-object)转换为tbl-header

时间:2016-04-23 01:51:53

标签: r dataframe

我有data.frame如下:

     types       long_name
     (chr)           (chr)
1  neighborhood Upper East Side
2  sublocality  Manhattan
3  postal_code  10021

我想将其转换如下:

     neighborhood    sublocality   postal_code
     (chr)           (chr)         (chr)
1  Upper East Side   Manhattan     10021

必须有一种快速简便的方法。

编者注:这不是作为R数据帧显示,而是作为dply tbl-object显示:

dput(as.tbl(dfrm))
structure(list(types = c("neighborhood", "sublocality", "postal_code"
), long_name = c("Upper East Side", "Manhattan", "10021")), .Names = c("types", 
"long_name"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-3L))

3 个答案:

答案 0 :(得分:2)

types设置为long_name向量上的名称,然后在其上运行as.data.frame.list()。假设df是您的数据框......

as.data.frame.list(
    with(df, setNames(long_name, types)), 
    stringsAsFactors = FALSE
)
#      neighborhood sublocality postal_code
# 1 Upper East Side   Manhattan       10021

或者,同样的事情略有不同......

as.data.frame(
    with(df, setNames(as.list(long_name), types)),
    stringsAsFactors = FALSE
)

如果您需要数字邮政编码,请在该列上运行as.numeric()。此外,由于您使用的是 dplyr ,因此可以通过将其包装在tbl_df()中来获得您的确切愿望结果。或者您可以使用

之类的内容在 dplyr 中完成所有操作
df %>%
    do(
        as.data.frame.list(
            setNames(.$long_name, .$types), 
            stringsAsFactors = FALSE
        )
    ) %>%
    tbl_df
# Source: local data frame [1 x 3]
#
#      neighborhood sublocality postal_code
#             (chr)       (chr)       (chr)
# 1 Upper East Side   Manhattan       10021

数据:

df <- structure(list(types = c("neighborhood", "sublocality", "postal_code"
), long_name = c("Upper East Side", "Manhattan", "10021")), .Names = c("types", 
"long_name"), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))

答案 1 :(得分:2)

我们可以使用DriverDAL.WriteFile( hDevice, writeBuffer, (uint)writeBuffer.Length, ref RealityWriteCount, IntPtr.Zero);

transpose

答案 2 :(得分:2)

坚持使用Hadleyverse,我们可以使用tidyr::spread从长到宽移动:

library(tidyr)

df %>% spread(types, long_name)
# Source: local data frame [1 x 3]
# 
#      neighborhood postal_code sublocality
#             (chr)       (chr)       (chr)
# 1 Upper East Side       10021   Manhattan