ffolkvar
ffolkvar

Reputation: 47

How to do a sum in R that gives the result in only one row

So I have a dataset in R of 1380 observations, with a dummy variable that is coded as 1 if the individual is rich. I would like to sum all the individuals with a value of 1 in the dataset, but whenever I create a new variable that sums its values with:

dataset_union$sum_high<- sum(dataset_union$high_inc)

The new variable it creates repeats the result of the sum over and over for every observation in the dataset. I would like this variable to show the result of the sum only in the first row, and leave blank the spaces below.

How could I code it?

Upvotes: 0

Views: 541

Answers (2)

arg0naut91
arg0naut91

Reputation: 14764

You could do:

dataset_union[1, "sum_high"] <- sum(dataset_union$high_inc == 1)

Upvotes: 1

ePoQ
ePoQ

Reputation: 463

You have to use the following conditional operator ==

Example:

ID <- c(1:10)
individuals <- c(1,1,2,1,5,3,3,2,1,6)
df <- data.frame(ID, individuals)
sum(df$individuals == 1)
4

Upvotes: 0

Related Questions