簡體   English   中英

如何基於列索引為列分配值

[英]How to assign a value to a column based on a column index

有一個數據框,我想根據給定的列索引分配一個計算值

df <- data.frame(a = c(2,4,7,3,5,3), b = c(8,3,8,2,6,1))

> df
   a b
 1 2 8     
 2 4 3
 3 7 8
 4 3 2
 5 5 6
 6 3 1

max <- apply(df, 1, which.max)
> max
[1] 2 1 2 1 2 1

addition <- apply(df, 1, sum)
> addition
[1] 10  7 15  5 11  4

然后將以下結果分配給df2我無法弄清楚的一些操作

> df2
  a  b
1 2 10
2 7  3
3 7 15
4 5  2
5 5 11
6 4  1

非常感謝您的想法和幫助。 謝謝

您可以使用cbind訪問每一行的選定列:

df2 = df
df2[cbind(1:nrow(df2),max)] = addition
df2
  a  b
1 2 10
2 7  3
3 7 15
4 5  2
5 5 11
6 4  1

在這里, cbind返回2列和6行的矩陣,我們使用矩陣子集對數據幀進行子集化。

您也可以直接使用向量化ifelse

with(df, cbind.data.frame(a = ifelse(a > b, a + b, a), b = ifelse(a > b, b, a + b)));
#  a  b
#1 2 10
#2 7  3
#3 7 15
#4 5  2
#5 5 11
#6 4  1

暫無
暫無

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

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