簡體   English   中英

如果行上的值匹配,則有條件替換

[英]Conditional replacement if values on a row match

我必須分析經濟學實驗中的數據。 因此,我有一個數據庫(14 976 obs),我將其分為兩部分:一個數據庫是供賣家使用的(類型1)(7488 obs),另一個數據庫供類型2的買家(7488 obs),每個數據庫都有212個變量。

在這里,您有兩個數據庫的一部分:

sellers
ID       Gender   Period   Matching group   Group    Type  Overcharging ...
654        1           1            73         1        1      NA
654        1           2            73         1        1      NA
654        1           3            73         1        1      NA
654        1           4            73         1        1      NA 
435        1           1            73         2        1      NA
435        1           2            73         2        1      NA
435        1           3            73         2        1      NA
435        1           4            73         2        1      NA 

buyers
 ID       Gender   Period   Matching group   Group    Type  Overcharging ...
 708        0           1            73         1        2       1
 708        0           2            73         1        2       0
 708        0           3            73         1        2       0
 708        0           4            73         1        2       1   
 546        1           1            73         2        2       0
 546        1           2            73         2        2       0
 546        1           3            73         2        2       1
 546        1           4            73         2        2       0

我有很多變量,例如“超額收費”,其中信息放置在買方行而不是賣方行中。 因此,我想做的就是替換賣家數據庫中的此信息。

為此,我有很多信息:在匹配組73中,我們知道例如在第1階段,對象708被過度收費(第1組中的一個)。 據我所知,這些人屬於第1組和第73組,我能夠確定在第1階段對他收取了超額費用的賣方:性別= 1的對象654。

因此,我想對賣家數據框添加過度收費(和其他一些)的買家價值,以分析賣家的行為,但要在正確的時期為正確的組和正確的匹配組進行分析。

謝謝 ! 感謝幫助...

您可以執行合並以獲取所需的信息。

# Select the Period, Matching Group, Group and Overcharging columns
# Selection by column ID (2nd, 3rd, 4th, 6th columns)
buyers_merge <- buyers[, c(2,3,4,6)]
# Rename the Overcharging column
names(buyers_merge)[4] <- "Overcharging_Buyers"
# Merge
sellers_merged <- merge(sellers, buyers_merge)

現在,如果我正確地編寫了上面的代碼,則應將Overcharging_Buyers列添加到Sellers表的副本中。 因為4個列名中有3個匹配,所以合並功能應自動在這些列上合並,並將不匹配的列添加為新列。 然后,您可以使用新添加的信息替換原始的“超額收費”列。

有關合並功能的更多信息,請參見此處

希望這可以幫助!

library(dplyr)
#join both dataframes on common columns
merged_df <- left_join(sellers, buyers, by=c('Period', 'Matching_group', 'Group'))

#find row_index which have missing "Overcharging" in sellers
idx <- which(is.na(merged_df$Overcharging.x))
merged_df[idx, "Overcharging.x"] <- merged_df[idx, "Overcharging.y"]

#drop unwanted columns to have the updated sellers
sellers_updated <- merged_df[,-c(dim(sellers)[2]+1: dim(merged_df)[2])]
colnames(sellers_updated) <- colnames(sellers)
sellers_updated

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM