将字符串中的第10个字符从R中数据帧的末尾移到第4个字符

问题描述 投票:0回答:4

我在数据框(类chr)内有字符串,但为简单起见,我仅描述1个字符串。

x <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N")

我想以相同的方式对这些字符串(在seq列中)进行重新排序,将第10个字符(“ J”)从末尾(现在为“ K”)移到第4个新位置,因此在此如果只是交换“ J”和“ K”。我猜好像是

mutate(seq_reordered = str_replace("pattern", "replacement", seq) %>%

或者也许

mutate(seq_reordered = sub(seq, "pattern", "replacement") %>%

但是正则表达式条件使我感到困惑,这对我来说并不明显

r regex
4个回答
1
投票

因为它是长度为14的vector,所以我们可以通过索引重新排列

x1 <- c(x[1:9], x[11], x[10], x[12:length(x)])

或者只是做索引

x1 <- x[c(1:9, 11:10, 12:length(x))]

1
投票

定义排列ix,然后应用它:

ix <- replace(seq_along(x), c(10, 11), c(11, 10))
x[ix]
##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "K" "J" "L" "M" "N"

如果您有一个数据框并需要将其应用于所有或某些行,则上述操作特别方便,因为可以一次完成所有操作。

DF <- DF[ix, ]

或仅将其应用于jy列:

DF[jy] <- DF[ix, jy]

尽管不适合大规模应用,另一种方法是直接在replace上使用x

replace(x, c(10, 11), x[c(11, 10)])

0
投票

经典交换问题?

temp <- x[10]
x[10] <- x[length(x) - 3] 
x[length(x) - 3] <- temp

0
投票

有几种解决问题的方法。

第一个更简单(在编程方面)是,如果您能够将字符串分成数据帧的多列,则可以使用dplyr中的整洁工具将数据帧转换为长格式&然后交换位置索引:

library(tidyverse)

# Generate data
set.seed(123456)
sequence_tibble1 <- tibble(c1 = sample(letters, 10), c2 = sample(letters, 10),
                    c3 = sample(letters, 10), c4 = sample(letters, 10),
                    c5 = sample(letters, 10), c6 = sample(letters, 10), 
                    c7 = sample(letters, 10), c8 = sample(letters, 10))

# Turn data frame long & turn the position variable numeric
sequence_tibble1 <- sequence_tibble1 %>%
  gather(key = 'position', value = 'character') %>%
  mutate(position = str_remove(position, 'c') %>% as.numeric())

# Create updated position2 variable that has the new positions you want
sequence_tibble1 <- sequence_tibble1 %>%
  mutate(position2 = case_when(
    position == 2 ~ 8,
    position == 8 ~ 2,
    TRUE ~ position
  ))

第二个选项可能有点像您想要的,但是它稍微依赖于使用purrr的更高级的函数编程,但是正在发生的事情应该很明显:


sequence <- list(c(sample(letters, 10)), c(sample(letters, 10)),
                 c(sample(letters, 10)), c(sample(letters, 10)))

sequence_tibble2 <- tibble(sequence)

swap_positions <- function(x) {

  x <- c(x[1:5], x[10], x[7:9], x[6])

}

sequence_tibble2 <- sequence_tibble2 %>%
  mutate(sequence2 = purrr::map(sequence, ~ swap_positions(.x)))

© www.soinside.com 2019 - 2024. All rights reserved.