定期将一列分成多行

时间:2018-11-16 04:57:24

标签: r split rows

我在一个csv文件中有一列数字,我想以固定的间隔将其断开并将其转置为多行。例如:

虚拟输入文件:

10
25  
09
04
14
100
01
10
100
04
04
01
04

预期的输出(定期中断3):

10 25 09 
04 14 100
01 10 100
04 04 01
04

我正在尝试通过使用for循环在 R 中进行此操作,但没有成功。我没有获得理想的输出,但是在同一列中有超过1000万个这样的点。因此,我不确定使用循环是否有效。我已经用Google搜索并看到了诸如split string at regular intervalsHow to split a string into substrings of a given length?这样的关于stackexchange的其他查询。但这并没有解决我的问题。

尽管如此,我们对此有所帮助。

4 个答案:

答案 0 :(得分:2)

这是一个基本的R选项。我们可以用select t.*, (case when x = 0 then 0 else row_number() over (partition by x, grp order by date) end) as y from (select t.*, countif(x = 0) over (order by date) as grp from t ) t 填充您的输入向量/列,使其长度变为三的倍数。然后,为三列中的每一列生成索引序列,并创建所需的数据框。

NA

答案 1 :(得分:2)

这是一种动态的tidyverse方法。应该适用于任何中断值。

set.seed(1)
df <- data_frame(x = sample(20, 10))

breaks <- 3

df %>% 
  mutate(
    id = rep(paste0("col", 1:breaks), length.out = nrow(.)),
    rn = ave(x, id, FUN = seq_along)
  ) %>% 
  spread(id, x) %>% 
  select(-rn)

# A tibble: 4 x 3
   col1  col2  col3
  <int> <int> <int>
1     6     8    11
2    16     4    14
3    15     9    19
4     1    NA    NA

# another example with breaks at 6
breaks <- 6

df %>% 
  mutate(
    id = rep(paste0("col", 1:breaks), length.out = nrow(.)),
    rn = ave(x, id, FUN = seq_along)
  ) %>% 
  spread(id, x) %>% 
  select(-rn)

# A tibble: 2 x 6
   col1  col2  col3  col4  col5  col6
  <int> <int> <int> <int> <int> <int>
1     6     8    11    16     4    14
2    15     9    19     1    NA    NA

答案 2 :(得分:1)

您可以在dplyr软件包中使用剪切功能。

dataframe %>% group_by(column) %>% 
mutate(new_variable = cut(column, breaks=quantile(column, c(0,0.25,0.5,0.75,1), labels=F))

#breaks into the intervals you require 
new_variable <- cut(as.numeric(dataset$column),breaks = 3) 

然后在重塑包中使用melt函数将列转置为行

答案 3 :(得分:1)

如果数据为矢量形式,则可以执行以下操作:

data <- c('10', '25', '09', '04', '14', '100', '01',
          '10', '100', '04', '04', '01', '04')
split(data, ceiling(seq_along(data) / 3))

如果它在数据框中,则应该这样做:

library(dplyr)
library(tidyr)
data <- data.frame(
  value = c('10', '25', '09', '04', '14', '100', '01',
        '10', '100', '04', '04', '01', '04'))
data %>%
  mutate(key = rep_len(c('a', 'b', 'c'), length.out = nrow(.))) %>%
  group_by(idx = as.integer((row_number() - 1) / 3)) %>% 
  spread(key, value) %>%
  select(-idx) %>%
  ungroup()
相关问题