简体   繁体   English

有条件地替换数据框中的值

[英]Conditional replacement of values in dataframe

I have two dataframes with seven descriptive data columns and a variable number of additional analysis columns (based on earlier steps in the code). 我有两个具有七个描述性数据列和可变数量的其他分析列的数据框(基于代码中的较早步骤)。 I want to replace some of the values in the analysis columns of dataframe1 with the corresponding values in dataframe2 based on a Boolean value in the first column of dataframe1 . 我想更换一些值的分析列dataframe1与相应的值dataframe2基于在第一列一个布尔值dataframe1

dataframe1 : dataframe1

structure(list(compare = c(1, 1, 0, 1, 1, 1, 0, 1), ID_TREE = 29338:29345, 
    ID_PLOT = c(1068L, 1068L, 1068L, 1068L, 1068L, 1068L, 1068L, 
    1068L), ID_CATEGORY = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), 
    ID_WOOD_SPGR_GREENVOL_DRYWT = c(28L, 28L, 28L, 7L, 28L, 28L, 
    28L, 28L), ID_BARK_SPGR_GREENVOL_DRYWT = c(25L, 25L, 25L, 
    18L, 25L, 25L, 25L, 25L), ID_BARK_VOL_PCT = c(2L, 2L, 2L, 
    10L, 2L, 2L, 2L, 2L), VOLCFGRS = c(3.21875, 6.576453125, 
    12.2406407654729, 0.863593268246, 1.15809306543472, 0.755301358016, 
    13.6662694477056, 4.549483421824)), row.names = c(NA, -8L
), class = c("data.table", "data.frame"), .internal.selfref = <pointer: (nil)>)

dataframe2 : dataframe2

structure(list(compare = c(1, 1, 0, 1, 1, 1, 0, 1), ID_TREE = 29338:29345, 
    ID_PLOT = c(1068L, 1068L, 1068L, 1068L, 1068L, 1068L, 1068L, 
    1068L), ID_CATEGORY = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), 
    ID_WOOD_SPGR_GREENVOL_DRYWT = c(28L, 28L, 28L, 7L, 28L, 28L, 
    28L, 28L), ID_BARK_SPGR_GREENVOL_DRYWT = c(25L, 25L, 25L, 
    18L, 25L, 25L, 25L, 25L), ID_BARK_VOL_PCT = c(2L, 2L, 2L, 
    10L, 2L, 2L, 2L, 2L), VOLCFGRS = c(-2.32258333333333, 5.81718680555556, 
    12.2406407654729, -32.9676545519935, -27.9506018960536, -38.5047101237694, 
    13.6662694477056, 1.9138577595677)), row.names = c(NA, -8L
), class = c("data.table", "data.frame"), .internal.selfref = <pointer: (nil)>)

So far I have gotten the following line of code to work for 1 column: 到目前为止,我已经获得了下面的代码行可用于1列:

df1[df1$compare==0,8]<- df2[df1$compare==0,8]

but when I try to abstract it to work for any number of columns I get an error: 但是当我尝试对其进行抽象以使其可用于任意数量的列时,出现错误:

df1[df1$compare==0,-(1:7)]<- df2[df1$compare==0,-(1:7)]

I also this and got a similar error: 我也这样,并得到了类似的错误:

df1[,-(1:7)]<- ifelse(df1$compare==0, df2[,-(1:7)], df1[,-(1:7)])

the two dataframes will always have the same number of columns. 这两个数据框将始终具有相同的列数。

Most simply you can "invert" your subsetting: 最简单的是,您可以“反转”您的子集:

df1[df1$compare==0,8:ncol(df1)] <- df2[df1$compare==0,8:ncol(df1)]

Another option would be to rbind the dijointed rows together. 另一种选择是rbind的dijointed排在一起。

rbind(df1[df1$compare!=0], df2[df1$compare==0])

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

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