ตอบ: วิธีเพิ่มคอลัมน์ใน data frame โดยอิงจากคอลัมน์อื่น
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อเพิ่มคอลัมน์ลงในกรอบข้อมูลใน 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
แหล่งข้อมูลเพิ่มเติม
วิธีเพิ่มคอลัมน์ใน data frame ใน R
วิธีเพิ่มคอลัมน์ว่างลงใน data frame ใน R
วิธีเพิ่มคอลัมน์ดัชนีลงใน data frame ใน R