【问题标题】:In R, how can I reorder variables of a tbl within a piped expression?在 R 中,如何在管道表达式中重新排序 tbl 的变量?
【发布时间】:2018-05-08 10:06:15
【问题描述】:

我已使用以下管道表达式加载了一个 .csv 文件、转换为 tbl、重命名变量、变异等:

h2020orgs <- read.csv2(file="C:/Users/Geoff/Desktop/Personal/DataCamp/R/R projects/Horizon_2020_orgs_data/cordis_h2020_orgs.csv") %>%
  tbl_df() %>%
  select(1:15) %>%
  rename(projectRcn = ï..projectRcn,
         orgType = activityType,
         orgRole = role,
         orgID = id,
         orgName = name,
         orgShortName = shortName) %>%
  mutate(orgTypeFull = recode(orgType,
                              HES = "Higher education",
                              OTH = "Other",
                              PRC = "Private company",
                              PUB = "Public body",
                              REC = "Research centre"))

使用names(h2020orgs)可以看到变量的索引:

names(h2020orgs)
 [1] "projectRcn"         "projectID"          "projectAcronym"     "orgRole"           
 [5] "orgID"              "orgName"            "orgShortName"       "orgType"           
 [9] "endOfParticipation" "ecContribution"     "country"            "street"            
[13] "city"               "postCode"           "organizationUrl"    "orgTypeFull"

我想移动“orgTypeFull”,使其与“orgType”相邻(紧接着)。我知道我可以使用以下独立调用来做到这一点:h2020orgs &lt;- h2020orgs[, c(...)] 但有没有办法将它包含在上面的管道表达式中?

【问题讨论】:

    标签: r dataframe dplyr piping


    【解决方案1】:

    使用select([...], orgType, orgTypeFull, [...]),其中[...] 表示“将其他列名放在那里”。

    【讨论】:

      【解决方案2】:

      您可以使用dplyr 中的select() 对列重新排序,可以按名称或索引。

      使用索引:

      ... %>% select(1:8, 16, 9:15)
      

      【讨论】:

        【解决方案3】:

        您可以使用 data.table 包中的setcolorder

        h2020orgs %>% setcolorder(c(1:8,16:9))
        

        或者没有管道:

        setcolorder(h2020orgs, c(1:8,16:9))
        

        【讨论】:

          猜你喜欢
          • 2022-07-07
          • 2013-01-15
          • 1970-01-01
          • 1970-01-01
          • 2021-05-23
          • 2011-02-05
          • 2023-03-29
          • 2020-01-31
          • 1970-01-01
          相关资源
          最近更新 更多