我有一个大矩阵,其中的一个子集如下:
mat<-read.table(text = "links X1 X2 X3 X4
a,b 1.2222 1.5147654 1.5147654 1.5147654
a,c 5.444 1.9763846 1.9763846 1.9763846
c,m 8.99999 1.5515179 -2.3816097 1.5515179
d,e 5.44643 2.2518252 2.2518252 -1.3523473
f,g 7.65656 1.8534944 1.8534944 1.8534944
f,k 2.5645 1.7646614 1.7646614 1.7646614
")
和以下数据帧:
df<-read.table(text="links values
a,b 2.716741
a,c 0
f,g 0
f,k 1.4534
",header=T,stringsAsFactors = F)
我想根据我的矩阵信息替换df的值,例如:
如果数据框的第一列中的值存在于矩阵的第一列中,则该列的前值应替换为矩阵中已存在的行中的一个值。矩阵中的替换值可以通过以下代码来区分:
x<-floor((df_dist_mat[i,2]-0.75)/0.5)+1
x值是指X1或...或X4列。最终结果应该是这样的:
links values
a,b 1.5147654
a,c 0
f,g 0
f,k 1.7646614
我编写了以下代码,但我不知道如何获得最终结果:
for (i in 1:nrow(df)) {
if (df[i,2]>0&& df[i,2]<=15) {
x<-floor((df[i,2]-0.75)/0.5)+1
}
}
有什么主意吗?
答案 0 :(得分:1)
对我有用:
1)您需要在header = TRUE
-数据帧中添加mat
2)根据您的评论,我调整了循环:
library(tidyverse) # you need dplyr and tidyr
df <- df %>% # prepare the df to splite the link column
separate(links, c("links1", "links2"))
for (i in 1:nrow(df)) {
if (df[i,3]>0 && df[i,3]<=15) {
var1 <- df[i, 1] # get character of link1
var2 <- df[i, 2] # get character of link2
x <- floor(((df[i,3]-0.75)/0.5)+1) # check the value and define the X column
# subset the mat dataset based on link names
# example "a,b" == "b,a" OR "a,b" == "a,b" OR "b,a" == "b,a"
foo <- mat %>%
select(links, paste0("X", x)) %>%
filter(links == paste0(var1, ",", var2) | links == paste0(var2, ",", var1))
df[i,3] <- foo[1,2]
}
}
# get back the old form of your df
df <- df %>%
unite(links, links1, links2, sep = ",")
输出将是:
links values
1 a,b 1.514765
2 a,c 0.000000
3 f,g 0.000000
4 f,k 1.764661