Reputation: 49
I have below data frame
col1 <- c("A","B", "A")
col2 <- c("C","D","D")
col3 <- c("E","E","E")
col4 <- c("F","F","H")
x <- data.frame(col1,col2,col3,col4)
Output of above frame is:
I want to replace characters to numbers, as below:
Upvotes: 1
Views: 45
Reputation: 886938
We can use lapply
from base R
x[] <- lapply(x, match, LETTERS)
x
# col1 col2 col3 col4
#1 1 3 5 6
#2 2 4 5 6
#3 1 4 5 8
Upvotes: 1
Reputation: 12559
Here is a solution with base R:
x[] <- match(as.matrix(x), unique(c(as.matrix(x))))
# > x
# col1 col2 col3 col4
# 1 1 3 5 6
# 2 2 4 5 6
# 3 1 4 5 7
Here is a shorter solution:
x[] <- as.integer(unlist(x))
x <- data.frame(col1=c("A","B", "A"), col2=c("C","D","D"), col3=c("E","E","E"), col4=c("F","F","H")
Upvotes: 2
Reputation: 94172
Here's a one-liner in base R that works with any number of columns and any names - nothing is hard-coded, so it works with any x
:
> setNames(data.frame(matrix(as.numeric(unlist(x)),ncol=ncol(x))),names(x))
col1 col2 col3 col4
1 1 3 5 6
2 2 4 5 6
3 1 4 5 7
Upvotes: 4
Reputation: 7153
x <- x %>%
unlist %>%
as.numeric %>%
matrix(ncol=4) %>%
data.frame
names(x) <- paste0("col", 1:4)
x
col1 col2 col3 col4
1 1 3 5 6
2 2 4 5 6
3 1 4 5 7
Upvotes: 2