简体   繁体   English

在R中加入3个不同长度的列

[英]Join 3 columns of different lengths in R

I have 3 columns我有 3 列

2 are the same length 2个一样长

1 is of a lesser length 1 长度较短

here are the columns:这是专栏:

column1 <- letters[1:10]

column2 <- letters[1:15]

column3 <- letters[1:15]

I want all 3 columns to be joined together but have the missing 5 values in column1 to be NA?我希望将所有 3 列连接在一起,但 column1 中缺少的 5 个值是否为 NA?

What can i do to achieve this?我该怎么做才能实现这一目标? a tibble?一个小问题?

You can change length of a vector 您可以更改向量的长度

column1 <- letters[1:10]
column2 <- letters[1:15]

length(column1) <- length(column2)

Now 现在

> column1
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" NA  NA  NA  NA  NA

We can wrap it in function 我们可以将其包装在函数中

cbind_dif <- function(x = list()){
    # Find max length
    max_length <- max(unlist(lapply(x, length)))

    # Set length of each vector as
    res <- lapply(x, function(x){
        length(x) <- max_length
        return(x)
    })

    return(as.data.frame(res))
}

# Example usage:
> cbind_dif(list(column1 = column1, column2 = column2))
   column1 column2
1        a       a
2        b       b
3        c       c
4        d       d
5        e       e
6        f       f
7        g       g
8        h       h
9        i       i
10       j       j
11    <NA>       k
12    <NA>       l
13    <NA>       m
14    <NA>       n
15    <NA>       o
n <- max(length(column1), length(column2), length(column3))
data.frame(column1[1:n],column2[1:n],column3[1:n])

   column1.1.n. column2.1.n. column3.1.n.
1             a            a            a
2             b            b            b
3             c            c            c
4             d            d            d
5             e            e            e
6             f            f            f
7             g            g            g
8             h            h            h
9             i            i            i
10            j            j            j
11         <NA>            k            k
12         <NA>            l            l
13         <NA>            m            m
14         <NA>            n            n
15         <NA>            o            o

Using cbind.fill from rowr package you can do it easily. 使用rowr包中的cbind.fill可以轻松实现。

library(rowr)

new<- cbind.fill(column1,column2,column3)

I hope this helps 我希望这有帮助

column1 <- letters[1:10]
column2 <- letters[1:15]
column3 <- letters[1:15]

tibble(a = c(column1, rep(NA, length(column2) - length(column1))), b = column2, c = column3)

# A tibble: 15 × 3
   a     b     c    
   <chr> <chr> <chr>
 1 a     a     a    
 2 b     b     b    
 3 c     c     c    
 4 d     d     d    
 5 e     e     e    
 6 f     f     f    
 7 g     g     g    
 8 h     h     h    
 9 i     i     i    
10 j     j     j    
11 NA    k     k    
12 NA    l     l    
13 NA    m     m    
14 NA    n     n    
15 NA    o     o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM