Having a data frame, how do I go about replacing all particular values along all rows and columns. Say for example I want to replace all empty records with NA
's (without typing the positions):
df <- data.frame(list(A=c("", "xyz", "jkl"), B=c(12, "", 100)))
A B
1 12
2 xyz
3 jkl 100
Expected result:
A B
1 NA 12
2 xyz NA
3 jkl 100
Like this:
Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:
For factors, zxzak's code already yields factors:
If in trouble, I'd suggest to temporarily drop the factors.
We can use data.table to get it quickly. First create df without factors,
Now you can use
and you can convert it back to a data.frame
If you only want to use data.frame and keep factors it's more difficult, you need to work with
where value is the name of every column. You need to insert it in a loop.
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace
""
and100
: