2

我有一个字母对列表df1。的当前尺寸df1是 1,5 :

df1= AC,AD,AE,AF,AG

我想向 df1 添加第二行,其中包含df1(dim: 2,5) 的反转元素,即:

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

我想一次访问第一行一个元素,将每个元素转换为字符串,然后将其反转。我试过了as.character(df1[1])toString(df1[1])但他们都给了我"1"结果。有人可以解释这个错误以及我该如何纠正它吗?

编辑:输出为str[df1]

   '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
4

3 回答 3

4

这是使用正则表达式的一种方法:

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)

结果:

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

结果是一个矩阵。可以将其转换为带有 的数据框as.data.frame

于 2013-06-07T16:40:58.187 回答
1

通常 as.matrix 是一种很好的强制方法。

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"

它回答了吗?

于 2013-06-07T16:40:51.077 回答
1

不确定这是最简单的方法,但这是一种可行的方法第一步是创建您的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

最后一步,我们将创建一个函数来反转字符串向量并将其应用于数据

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
于 2013-06-07T16:41:03.913 回答