【问题标题】:Function to add empty colum in data frame when column of another df is different in R当另一个df的列在R中不同时,在数据框中添加空列的函数
【发布时间】:2014-02-21 20:40:22
【问题描述】:

我有两个数据框 df1 和 df2。 df1 包含:

t <- c(0,2,0,0,2,0,2)

cool <- c(0,1,0,0,1,0,1)
bad <- c(1,0,1,1,0,1,0)
great <- c(1,1,0,0,0,0,1)

df1 <- data.frame(t, cool, bad, great)

df2 包含一个额外的列

no <- c(1,0,1,0,0,1,1)

df2 <- data.frame(t, cool, bad, great, no)

现在我想创建一个函数,将空列添加到 df1(仅填充零),并且此空列的名称对应于与 df2 不同的列(这里是列“no”那应该是空的并添加到df1)。此功能应适用于所有其他不常见的列,以便自动将空列添加到 df1。 开始可能是这样的

addcolumn <- function(df1, df2) {
 w<- which((df1) != ncol(df2)){
   }
 }

谢谢你的回答

【问题讨论】:

    标签: r function dataframe


    【解决方案1】:

    你可以试试这个:

    # names of columns in df2 that are not in df1
    cols <- names(df2)[!(names(df2) %in% names(df1))]
    
    # ...or
    cols <- setdiff(names(df2), names(df1))
    
    # add cols from d2 to df1
    df3 <- cbind(df1, df2[ , cols, drop = FALSE])
    
    # set cols from df1 to zero
    df3[ , cols] <- 0
    df3
    
    #   t cool bad great no
    # 1 0    0   1     1  0
    # 2 2    1   0     1  0
    # 3 0    0   1     0  0
    # 4 0    0   1     0  0
    # 5 2    1   0     0  0
    # 6 0    0   1     0  0
    # 7 2    1   0     1  0
    

    更新以下评论:一个更通用的解决方案,其中df2 的行数可能与 df1 不同。

    df2 <- data.frame(t = 1:8,
                      no = 1:8,
                      yes = 9:16) 
    
    # names of columns in df2 that are not in df1
    cols <- names(df2)[!(names(df2) %in% names(df1))]
    
    # create a matrix of zeros
    # number of rows equals number of rows in df1
    # number of columns equals number of new variables   
    m <- matrix(0, nrow = nrow(df1), ncol = length(cols), dimnames = list(NULL, cols))
    
    df3 <- cbind(df1, m)
    df3
    

    【讨论】:

    • 很高兴听到您发现我的回答很有帮助!干杯。
    • 我还有一个问题。当 df2
    • 恐怕我不太明白你的意思。您评论中的df2 看起来与您问题中的df2 相同。
    • 如果 df2 中的 no2
    • @Charlotte,请查看我的更新答案。作为 SO 的新用户,您还可以花时间阅读here。干杯。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    相关资源
    最近更新 更多