gpt4 book ai didi

r - 在 R : How to replace NA in a Vector found between two integers

转载 作者:行者123 更新时间:2023-12-04 17:42:56 25 4
gpt4 key购买 nike

我有以下向量:

A:(NA NA NA NA 1 NA NA 4 NA NA 1 NA NA NA NA NA 4 NA 1 NA 4)

我想用 2 替换 1 和 4 之间的所有 Nas(但不是 4 和 1 之间的 Nas)

您是否会为此任务推荐/使用任何方法?

它也可以作为数据帧进行管理:
 A 
----
NA
NA
NA
NA
1
NA
NA
4
NA
NA
1
NA
NA
NA
NA
NA
4
NA
1
NA
4
----

编辑 :
1.我将字符串“Na”更改为NA。

解决方案/更新
感谢大家的见解。我从他们那里学到了针对我的案例提出以下解决方案。我希望它对其他人有用:
A <- c(df$A)

index.1<-which(df$A %in% c(1)) # define location for 1s in A
index.14<-which(df$A %in% c(1,4)) # define location for 1s and 4s in A

loc.1<-which(index.14 %in% index.1) # location of 1s in index.14
loc.4<-loc.1+1 # location of 4s relative to 1s in index.14

start.i<-((index.14[loc.1])+1) # starting index for replacing with 2
end.i<-((index.14[loc.4])-1) # ending index for replacing with 2 in index

fill.v<-sort(c(start.i, end.i))# sequence of indexes to fill-in with # 2

# create matrix of beginning and ending sequence
fill.m<-matrix(fill.v,nrow = (length(fill.v)/2),ncol = 2, byrow=TRUE)

# create a list with indexes to replace
list.1<-apply(fill.m, MARGIN=1,FUN=function(x) seq(x[1],x[2]))

# unlist list to use as the indexes for replacement
list.2<-unlist(list.1)

df$A[list.2] <- 2 # replace indexed location with 2

最佳答案

假设 A如末尾的注释中可重复显示的那样,显示的 cumsum 的差异为 1 和 4 之间的元素提供了 TRUE,并且下一个条件消除了端点。最后,我们将剩下的位置为 TRUE 的位置替换为 2。

replace(A, (cumsum(A == 1) - cumsum(A == 4)) & (A == "Na"), 2)

给予:
 [1] "Na" "Na" "Na" "Na" "1"  "2"  "2"  "4"  "Na" "Na" "1"  "2"  "2"  "2"  "2" 
[16] "2" "4" "Na" "1" "2" "4"

NA值

R 区分大小写,Na 与 NA 不同。问题中的样本数据显示的是 Na 值而不是 NA 值,但如果实际上意味着是具有 NA 值的数值向量,如 AA在下面的注释中,然后将表达式修改为如下所示:
replace(AA, cumsum(!is.na(AA) & AA == 1) - cumsum(!is.na(AA) & AA == 4) & is.na(AA), 2)

给予:
[1] NA NA NA NA  1  2  2  4 NA NA  1  2  2  2  2  2  4 NA  1  2  4

笔记
A <- c("Na", "Na", "Na", "Na", "1", "Na", "Na", "4", "Na", "Na", 
"1", "Na", "Na", "Na", "Na", "Na", "4", "Na", "1", "Na", "4")

AA <- as.numeric(replace(A, A == "Na", NA))

关于r - 在 R : How to replace NA in a Vector found between two integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54985964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com