【问题标题】:combining two dataframe rows of data to the same dataframe row while having the same row size using R使用 R 将两个数据帧行数据组合到同一数据帧行,同时具有相同的行大小
【发布时间】:2020-04-04 06:35:26
【问题描述】:

我是相对较新的 R,我有两个这样的数据框:

#view(df1) (10x1) dataframe
# A
# NA
# C
# NA
# E
# NA
# G
# NA
# I
# NA
#view(df2) (10x1) dataframe
# B
# NA
# D
# NA
# F
# NA
# H
# NA
# J
# NA

我希望我在 R 中的输出如下

#output

#view(df1) (10x1) dataframe

# A
# B
# C
# D
# E
# F
# G
# H
# I
# J

我曾尝试使用 rbind,但它似乎会增加行大小,我想保持行大小一致。我也尝试过使用合并,但似乎没有得到正确的输出

输入:

df1:

structure(list(A = c("A", NA, "C", NA, "E", NA, "G", NA, "I")), class = "data.frame", row.names = c(NA, 
-9L))

df2:

structure(list(B = c("B", NA, "D", NA, "F", NA, "H", NA, "J")), class = "data.frame", row.names = c(NA, 
-9L))

【问题讨论】:

  • df3 = rbind(df1, df2); df3 = df3[!(is.na(df3))] 怎么样?这是你的意图吗?

标签: r


【解决方案1】:

这是我的非优雅解决方案:

由于您的行对齐并且没有交错,您需要向数据框添加一些 NA 行:

library(dplyr)

# Add NA row to the end of df1
df1[nrow(df1)+1,] <- NA

# Add NA row to the beginning of df2
df2 <- rbind(c(NA),df2)

# Merge them with `coalesce`
df3 <- data.frame(coalesce(df1$A,df2$B))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2021-08-15
    • 2019-05-14
    • 2017-01-03
    相关资源
    最近更新 更多