【问题标题】:Handling numbers within character strings in R在 R 中处理字符串中的数字
【发布时间】:2018-10-15 04:44:38
【问题描述】:

我有以下(包含数字的)字符向量:

nums = c("1, 2", "1, 2, 4", "2, 4", "1, 2, 3, 4, 5", "2, 3, 5", NA, NA, NA, NA)

我想设置一个算法来测试nums 中元素的n 子集是否包含n 唯一数字,然后从其他元素中删除这些数字。其中n 是从19 的任意数字。

在上面的示例中,由于第一个 3 元素仅包含 3 数字:1, 2, 4,因此应从其他元素中删除这些数字。所以输出会是这样的:

nums = c("1, 2", "1, 2, 4", "2, 4", "3, 5", "3, 5", NA, NA, NA, NA)

请注意,它可能是具有2 唯一编号的2 元素或具有4 唯一编号的4 元素,等等。

我想将最终输出保留为与原始长度相同的字符向量。

【问题讨论】:

  • 首先,您应该将字符向量转换为数字向量列表。如果您需要一个字符向量(出于某种未指定和奇怪的原因),您应该在所有数据操作之后在最后创建它。
  • 对第一步和最后一步的好建议,@Ronald。中间呢?

标签: r string unique


【解决方案1】:

如果我理解得很好,你可以应用以下内容:

library(stringr)
library(readr)
library(purrr)
nums = c("1, 2", "1, 2, 4", "2, 4", "1, 2, 3, 4, 5", "2, 3, 5", NA, NA, NA, NA)

# create a list within each element is a character element of nums
num_into_list <- stringr::str_split(nums, ",")

# convert to numbers
num_into_list <- purrr::map(num_into_list, readr::parse_number)

# collect unique numbers from the nth first subset of the list (example 3)
not_allowed <- unique(unlist(num_into_list[1:3]))

# filter only values on the rest of the subset that doesn't contain
# values in not_allowed vector, using a logical subsetting operation
# inside of  anonymous function (purrr shortcut to create this)   
output_list <- c(num_into_list[1:3],   # first 3 subset are the same
                 purrr::map(num_into_list[4:9], ~ .[!(. %in% not_allowed)]))

# finally convert into a chr vector
output <- unlist(output_list)

如果参数化第 n 个第一个子集以创建 not_allowed 向量和向量的长度,然后重构列表(在 output_list 步骤索引中),您可以使用上述代码创建一个函数。

【讨论】:

  • 感谢@Cristobal 的回答。问题是我不知道每个向量的 n 值以及哪些元素包含not_allowed 数字,代码应该首先确定它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 2021-01-26
  • 2010-11-14
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多