如何通过覆盖现有行来附加两个数据帧

时间:2016-11-03 09:15:59

标签: r

我有一个数据框说df。我从df中提取了5%的样本并创建了一个新的数据帧df1,以便在数据集中进行一些操作。现在我需要将df1附加到df并覆盖现有的df1行,因为它是df的子集。

我尝试使用

提取df中不存在的行
    df2 <- subset(df, !(rownames(df) %in% rownames(df1[])))

但这没有用。 任何人都可以帮忙。

2 个答案:

答案 0 :(得分:2)

保存过滤器并重复使用

set.seed(357)
xy <- data.frame(col1 = letters[1:5], col2 = runif(5))

  col1       col2
1    a 0.10728121
2    b 0.05504568
3    c 0.27987766
4    d 0.22486212
5    e 0.65348521


your.condition <- xy$col1 %in% c("c", "d")
newxy1 <- xy[your.condition, ]
newxy1$col2 <- 1:2

xy[your.condition, "col2"] <- newxy1$col2
xy

  col1       col2
1    a 0.10728121
2    b 0.05504568
3    c 1.00000000
4    d 2.00000000
5    e 0.65348521

答案 1 :(得分:1)

您应该始终尝试制作reproducible example,以便其他人轻松帮助您

我试图在mtcars数据集

的帮助下做到这一点
#Copied mtcars data into df
df = mtcars
# sample 5 rows from df 
df1 = df[sample(1:nrow(df), 5), ]
# did few manipulations in the dataset
df1 = df1 * 2
# overwrite the existing rows of df1 as it is a subset of df
df[rownames(df1), ] <- df1
相关问题