user2211355
user2211355

Reputation: 57

Converting data frame element to string in R

I have a list of letter pairs in df1. The current dimension of df1 is 1,5 :

df1= AC,AD,AE,AF,AG

I want to add a second row to df1 containing the reversed elements of df1 (dim: 2,5), i.e.:

df1= AC,AD,AE,AF,AG
     CA,DA,EA,FA,GA

I want to access the first row one element at a time, convert each to string, and then reverse it. I've tried as.character(df1[1]) and toString(df1[1]) but they both give me "1" as the result. Could someone explain the error and how I could rectify it?

EDIT: The output for str[df1] is :

   'data.frame':    1 obs. of  5 variables:
     $ V1  : Factor w/ 1 level "AC": 1
     $ V2  : Factor w/ 1 level "AD": 1
     $ V3  : Factor w/ 1 level "AE": 1
     $ V4  : Factor w/ 1 level "AF": 1
     $ V5  : Factor w/ 1 level "AG": 1

Upvotes: 3

Views: 33111

Answers (3)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

Here is one way to do it with regular expressions:

df1 <- read.csv(text = "AC,AD,AE,AF,AG", header = FALSE) # your data frame

tmp <- sapply(df1, as.character) # a character vector

matrix(c(tmp, sapply(df1, sub, pattern = "(.)(.)", replacement = "\\2\\1")), 
       2, byrow = TRUE)

The result:

     [,1] [,2] [,3] [,4] [,5]
[1,] "AC" "AD" "AE" "AF" "AG"
[2,] "CA" "DA" "EA" "FA" "GA"

The result is a matrix. It can be converted into a data frame with as.data.frame.

Upvotes: 4

dickoa
dickoa

Reputation: 18437

Not sure that is the easiest way to do that but here is one approach that works The first step is to create your data.frame

dat <- Reduce(data.frame,
              c("AC", "AD", "AE", "AF", "AG"))
names(dat) <- paste0("V", 1:ncol(dat))
str(dat)

## 'data.frame':    1 obs. of  5 variables:
##  $ V1: Factor w/ 1 level "AC": 1
##  $ V2: Factor w/ 1 level "AD": 1
##  $ V3: Factor w/ 1 level "AE": 1
##  $ V4: Factor w/ 1 level "AF": 1
##  $ V5: Factor w/ 1 level "AG": 1

And in a final step, we will create a function to reverse vector of string and apply it to the data

str_rev <- function(string)
    paste(rev(unlist(strsplit(string, ""))), collapse = "")

str_rev <- Vectorize(str_rev, USE.NAMES = FALSE)


rbind(dat,
      t(apply(dat, 1, str_rev))
      )

##   V1 V2 V3 V4 V5
## 1 AC AD AE AF AG
## 2 CA DA EA FA GA

Upvotes: 1

user1265067
user1265067

Reputation: 897

generally as.matrix is a good coercion method.

df <- data.frame(matrix(c("AC","AD","AE","AF","AG"), nrow=1))
df
X1 X2 X3 X4 X5
1 AC AD AE AF AG

sapply(df, function(x) paste(rev(strsplit(as.matrix(x), "")[[1]]), collapse=""))
  X1   X2   X3   X4   X5
"CA" "DA" "EA" "FA" "GA"

does it answer?

Upvotes: 1

Related Questions