Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 327
user2211355 Avatar asked Dec 13 '25 05:12

user2211355


1 Answers

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.

like image 60
Sven Hohenstein Avatar answered Dec 15 '25 18:12

Sven Hohenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!