【问题标题】:Tidyverse R: how to change a tuple-table into straight tibble?Tidyverse R:如何将 tuple-table 更改为直 tibble?
【发布时间】:2018-03-17 04:18:06
【问题描述】:

我想执行以下操作,将数据的元组样式行(不带标题)更改为带有标题的表,使用 Tidyverse。新的命令 collect 显然可以处理这个问题。

我怎样才能把宽桌子拼成直桌或使用其他一些现代的 Tidyverse 工具?

library(tidyverse)
INLINE_LOAD ="Car,Merse,Speed,10,Other,ot
Car,Ferra,Speed,20,Other,ot2
Car,Volve,Speed,30,Other,ot3
Car,Miiss,Speed,40,Other,ot4"

想要的输出

Car,Speed,Other
Merse,10,ot
Ferra,20,ot2
Volve,30,ot3
Miiss,40,ot4

【问题讨论】:

  • 你有列名还是第一行是列名
  • @akrun 没有列名作为标题。列名在每一行上:每个奇数值是一个列名。列名是CarSpeedOther
  • 反对者请评论原因。
  • 不是反对者,但这里有几个原因:没有可重复的示例,没有尝试解决您的问题。当您发布的只是我有这个并且我想要这个时,人们往往会感到沮丧

标签: r tidyverse


【解决方案1】:

与tidyverse:

df %>% select(Car = 2, Speed = 4, Other = 6)

结果:

# A tibble: 4 x 3
     Car Speed  Other
  <fctr> <int> <fctr>
1  Merse    10     ot
2  Ferra    20    ot2
3  Volve    30    ot3
4  Miiss    40    ot4

使用基础 R:

dfnew <- df[,c(FALSE,TRUE)]
names(dfnew) <- unlist(unique(df[,c(TRUE,FALSE)]))

结果:

> dfnew
    Car Speed Other
1 Merse    10    ot
2 Ferra    20   ot2
3 Volve    30   ot3
4 Miiss    40   ot4

【讨论】:

  • library(tidyverse);df &lt;- read_delim("Input.csv", ",");dfnew &lt;- df[,c(FALSE,TRUE)] 触发错误Error: Length of logical index vector must be 1 or 6 (the number of rows), not 2
  • @hhh 这是因为 tidyverse 与数据框格式混淆;我也为我的答案添加了一个 tidyverse 解决方案;对于基础 R,您可以执行 dfnew &lt;- as.data.frame(df)[,c(FALSE,TRUE)]
  • @hhh 最后添加了另一个解决方案,希望对您有所帮助
  • 是的,这是迄今为止最优雅的 +1,也许你可以简化答案——这有点难读,我只能得到最后一个使用 InlineLoad INLINE_LOAD ="Car,Merse,Speed,10,Other,ot Car,Ferra,Speed,20,Other,ot2 Car,Volve,Speed,30,Other,ot3 Car,Miiss,Speed,40,Other,ot4"; df &lt;- read_delim(INLINE_LOAD, ",", col_names=FALSE)跨度>
【解决方案2】:

我们首先使用内联加载,然后应用以下转换

library(tidyverse)
INLINE_LOAD ="Car,Merse,Speed,10,Other,ot
Car,Ferra,Speed,20,Other,ot2
Car,Volve,Speed,30,Other,ot3
Car,Miiss,Speed,40,Other,ot4"

read_delim(INLINE_LOAD, ",", col_names=FALSE) %>% 
    select(c(2,4,6)) %>% 
    select(Car=X2,Speed=X4,Other=X6)

重命名列并仅选择奇数列。有一个更优雅的解决方案here,只有一个选择。

当有大量列时,这不是一个非常优雅的解决方案。

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2011-12-28
    • 2015-09-19
    相关资源
    最近更新 更多