Behzad Nazarbakhsh
Behzad Nazarbakhsh

Reputation: 49

Converting dataframe

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:

1

I want to replace characters to numbers, as below:

2

Upvotes: 1

Views: 45

Answers (4)

akrun
akrun

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

jogo
jogo

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))

data:

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

Spacedman
Spacedman

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

Adam Quek
Adam Quek

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

Related Questions