![](/img/trans.png)
[英]R: how to combine the value of a column in two rows together, if these two rows share same character strings in another two columns
[英]R: how to merge two columns (column addition) while ignoring rows with same value
看來您只想合並這兩列,而不是添加( +
)意義上的添加它們。 也許想想拉鏈。 或者兩條路合並為一條。
這兩列似乎是由兩個獨立的過程創建的,第一個看起來更准確。 但是,在導入鏈接中提供的數據后,它們具有完全相同的值。
test <- read.csv("test.csv", row.names = 1)
options(digits=10)
head(test)
Sample_ID Sample_Intensity_RTC Sample_Intensity_nRTC
1 191017QMXP002 NA NA
2 191017QNXP008 41293681.00 41293681.00
3 191017CPXP009 111446376.86 111446376.86
4 191017HPXP010 92302936.62 92302936.62
5 191017USXP001 NA 76693308.46
6 191017USXP002 NA 76984658.00
在任何情況下,要將它們組合起來,我們可以使用ifelse
和條件is.na
作為第一列。
test$new_col <- ifelse(is.na(test$Sample_Intensity_RTC),
test$Sample_Intensity_nRTC,
test$Sample_Intensity_RTC)
head(test)
Sample_ID Sample_Intensity_RTC Sample_Intensity_nRTC new_col
1 191017QMXP002 NA NA NA
2 191017QNXP008 41293681.00 41293681.00 41293681.00
3 191017CPXP009 111446376.86 111446376.86 111446376.86
4 191017HPXP010 92302936.62 92302936.62 92302936.62
5 191017USXP001 NA 76693308.46 76693308.46
6 191017USXP002 NA 76984658.00 76984658.00
sapply(test, function(x) sum(is.na(x)))
Sample_ID Sample_Intensity_RTC Sample_Intensity_nRTC new_col
0 126 143 108
您還可以使用 dplyr 中的coalesce
function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.