A: 데이터 프레임의 값을 조건부로 바꾸는 방법
다음 방법 중 하나를 사용하여 데이터 프레임의 값을 조건부로 바꿀 수 있습니다.
방법 1: 전체 데이터 프레임에 걸쳐 값 바꾸기
#replace all values in data frame equal to 30 with 0 df[df == 30 ] <- 0
방법 2: 특정 열의 값 바꾸기
#replace values equal to 30 in 'col1' with 0 df$col1[df$col1 == 30 ] <- 0
방법 3: 다른 열을 기준으로 특정 열의 값 바꾸기
#replace values in col2 with 0 based on rows in col1 equal to 30 df$col2[df$col1 == 30 ] <- 0
다음 예에서는 다음 데이터 프레임을 사용하여 실제로 각 메서드를 사용하는 방법을 보여줍니다.
#create data frame
df <- data. frame (team=c('A', 'A', 'B', 'B', 'B'),
points=c(99, 90, 90, 88, 88),
assists=c(33, 28, 31, 30, 34),
rebounds=c(30, 30, 24, 24, 28))
#view data frame
df
team points assists rebounds
1 A 99 33 30
2 A 90 28 30
3 B 90 31 24
4 B 88 30 24
5 B 88 34 28
방법 1: 전체 데이터 프레임에 걸쳐 값 바꾸기
다음 코드는 데이터 프레임에서 30과 같은 모든 값을 0으로 바꾸는 방법을 보여줍니다.
#replace all values in data frame equal to 30 with 0 df[df == 30 ] <- 0 #view updated data frame df team points assists rebounds 1 A 99 33 0 2 A 90 28 0 3 B 90 31 24 4 B 88 0 24 5 B 88 34 28
방법 2: 특정 열의 값 바꾸기
다음 코드는 “points” 열의 90과 같은 모든 값을 0으로 바꾸는 방법을 보여줍니다.
#replace all values equal to 90 in 'points' column with 0 df$points[df$points == 90 ] <- 0 #view updated data frame df team points assists rebounds 1 A 99 33 30 2 A 0 28 30 3 B 0 31 24 4 B 88 30 24 5 B 88 34 28
방법 3: 다른 열을 기준으로 특정 열의 값 바꾸기
다음 코드는 “points” 열의 값을 0으로 바꾸는 방법을 보여줍니다. 여기서 “team” 열의 값은 “B”입니다.
#replace all values equal to 90 in 'points' column with 0 df$points[df$team == ' B '] <- 0 #view updated data frame df team points assists rebounds 1 A 99 33 30 2 A 90 28 30 3 B 0 31 24 4 B 0 30 24 5 B 0 34 28
추가 리소스
다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
A: 여러 열을 기반으로 데이터 프레임을 병합하는 방법
A: 다른 열을 기반으로 데이터 프레임에 열을 추가하는 방법