user13582101
user13582101

Reputation: 31

Error in `$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) : replacement has 0 rows, data has 526

Have a CSV file with wages.

Attempting to convert a qualitative variable into a numerical variable. The variable is "marital", where 1 denotes being married and 0 denotes being unmarried.

wages = read.csv("Desktop/wages.csv")

wages$marital1=as.numeric(wages$marital1=="married")

Keep getting

Error in `$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) :
replacement has 0 rows, data has 526

Upvotes: 3

Views: 25602

Answers (3)

Sandy
Sandy

Reputation: 1148

It might be a bit late, but if you are still looking for a solution, you can try running the following command on your data frame. Note that, this command will run on the entire data frame wages:

wages = type.convert(wages, as.is = TRUE)

To only manipulate selective columns i.e., to convert them into factor, you can do as follows:

# Column selection can be done by name or by the position of the column
names = c('marital1') # Select as many or as few columns
wages[,names] <- lapply(wages[,names] , factor)

Correspondingly, you can convert some or all variables into character as follows:

names = c('marital1') # You can select as many or as few columns as you want
wages[,names] <- sapply(wages[,names] , factor)

Hope it helps!

Upvotes: 0

聂秀泉
聂秀泉

Reputation: 51

You need to check your variable name (column name), the reason for this problem is usually because the variable name in your function is different from the variable name (column name) in the data frame.

Upvotes: 5

dvd280
dvd280

Reputation: 962

try :

wages$marital1 = (wages$marital1=="married") * 1

Upvotes: 0

Related Questions