A:如何根据其他列向数据框添加列


您可以使用以下基本语法根据其他列的值将列添加到 R 中的数据框中:

 #add new column 'col3' with values based on columns 1 and 2
df$col3 <- with (df, ifelse (col1 > col2, value_if_true, value_if_false))

以下示例展示了如何在实践中使用此语法。

示例 1:根据其他列添加字符列

下面的代码展示了如何根据数据框中其他列的值添加新的字符列:

 #create data frame
df <- data. frame (team=c('Mavs', 'Cavs', 'Spurs', 'Nets'),
                 scored=c(99, 90, 84, 96),
                 allowed=c(95, 80, 87, 95))

#view data frame
df

   team scored allowed
1 Mavs 99 95
2 Cavs 90 80
3 Spurs 84 87
4 Nets 96 95

#add 'result' column based on values in 'scored' and 'allowed' columns
df$result <- with (df, ifelse (scored > allowed, ' Win ', ' Loss '))

#view updated data frame
df

   team scored allowed result
1 Mavs 99 95 Win
2 Cavs 90 80 Win
3 Spurs 84 87 Losses
4 Nets 96 95 Win

下面的代码展示了如何添加一个新的字符列,该列结合了两个ifelse()函数以在新列中产生三个潜在值:

 #create data frame
df <- data. frame (team=c('Mavs', 'Cavs', 'Spurs', 'Nets'),
                 scored=c(99, 90, 84, 96),
                 allowed=c(95, 80, 87, 95))

#view data frame
df

   team scored allowed
1 Mavs 99 95
2 Cavs 90 80
3 Spurs 84 87
4 Nets 96 95

#add 'quality' column based on values in 'scored' and 'allowed' columns
df$quality <- with (df, ifelse (scored > 95, ' great ',
                         ifelse (scored > 85, ' good ', ' bad ')))

#view updated data frame
df

   team scored allowed quality
1 Mavs 99 95 great
2 Cavs 90 80 good
3 Spurs 84 87 bad
4 Nets 96 95 great

示例 2:根据其他列添加数字列

下面的代码展示了如何根据其他列的值向数据框中添加新的数字列:

 #create data frame
df <- data. frame (team=c('Mavs', 'Cavs', 'Spurs', 'Nets'),
                 scored=c(99, 90, 84, 96),
                 allowed=c(95, 80, 87, 95))

#view data frame
df

   team scored allowed
1 Mavs 99 95
2 Cavs 90 80
3 Spurs 84 87
4 Nets 96 95

#add 'lower_score' column based on values in 'scored' and 'allowed' columns
df$lower_score <- with (df, ifelse (scored > allowed, allowed, scored))

#view updated data frame
df

   team scored allowed lower_score
1 Mavs 99 95 95
2 Cavs 90 80 80
3 Spurs 84 87 84
4 Nets 96 95 95

其他资源

如何在R中向数据框添加列
如何在R中的数据框中添加空列
如何在R中向数据框添加索引列

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注