【问题标题】:Assigning names to certain ranges of values in vector based on their positions [R]根据位置 [R] 为向量中的某些值范围分配名称
【发布时间】:2021-12-07 04:28:06
【问题描述】:

我有一个存储一些值的数字向量,例如:

vec <- sample(200:800, 20, replace = TRUE)

还有两个数值变量表示这个向量中的某些位置,例如:

pos1 <- 6
pos2 <- 12

我想将给定 vec 中的所有值命名为 pos2 "end" 和这两个坐标之间的值 "middle"。

我是 R 的初学者。我知道如何使用多行代码来做到这一点,但如果有一些更直接和更好优化的解决方案,我将不胜感激。

这是我的代码:

vec <- sample(200:800, 20, replace = TRUE)
positions <- 1:length(vec)
pos1 <- 6
pos2 <- 12

front <- positions[1:pos1-1]
middle <- positions[pos1:pos2]
end <- positions[(pos2+1):length(positions)]

segmentation <- c(rep("front", length(front)), rep("middle", length(middle)), rep("end", length(end)))
vec2 <- vec
vec2 <- setNames(segmentation, vec)

我也知道如何通过创建一个 df 然后提取命名的 vec 来解决这个问题,但我想避免这种情况。

非常感谢您的帮助。

【问题讨论】:

  • 您可以使用findInterval() - 例如setNames(factor(findInterval(seq_along(vec), c(pos1, pos2), rightmost.closed = TRUE ), labels = c("front", "middle", "end")), vec)cut() - setNames(cut(seq_along(vec), c(0,5, 12, Inf), labels = c("front", "middle", "end")), vec).
  • 这是一种完全有效的方法。它是合乎逻辑的,可读的并且不包含多余的命令,最重要的是 - 做你想要的。编写易于理解的代码比追逐最短的命令更重要。
  • 非常感谢您的回复。最好的问候。
  • 如果下面的解决方案解决了您的问题,我们鼓励您单击复选标记接受它
  • @Skaqqs 是的,我使用了 ifelse 方法,因为它便于我进一步操作,虽然 findInterval() 也很酷。

标签: r vector names


【解决方案1】:

在您的问题中,您描述了您的逻辑问题,那么为什么不使用 ifelse() 将文字中的逻辑转换为逻辑:

# Create a toy vector with dummy names
vec <- sample(200:800, 20, replace = TRUE)
names(vec) <- 1:length(vec)

# Define criteria for naming
pos1 <- 6
pos2 <- 12

# Use logic to define names in toy vector
names(vec) <- ifelse(as.numeric(names(vec)) < pos1,
                     yes = "front",
                     no = ifelse(as.numeric(names(vec)) > pos2,
                                 yes = "back",
                                 no = "middle"))
vec
#>  front  front  front  front  front middle middle middle middle middle middle 
#>    762    205    469    484    653    491    505    432    783    345    366 
#> middle   back   back   back   back   back   back   back   back 
#>    664    498    706    248    547    317    695    749    225
Created on 2021-10-20 by the reprex package (v2.0.1)

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2017-06-21
    • 1970-01-01
    • 2015-09-16
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多