Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以使用R中另一个数据帧的相应值来划分数据帧的每一列吗?_R_Dataframe - Fatal编程技术网

我可以使用R中另一个数据帧的相应值来划分数据帧的每一列吗?

我可以使用R中另一个数据帧的相应值来划分数据帧的每一列吗?,r,dataframe,R,Dataframe,我在R中有两个数据帧,如下所示: # A B C D # 4 12 1 6 # 3 5 3 8 # 6 1 9 4 其中A、B、C、D是列名, 及 其中id和value是列名 我试图编写一个代码,将每列中的所有值除以第二个数据帧中的“值”。 我尝试在这里搜索,使用一些软件包,手工编写自己的循环,但没有任何效果。我的数据帧有数千列,所以我无法手动键入。请帮助并感谢您。一个dplyr解决方案可以是: df1 %>% rowwise() %>% muta

我在R中有两个数据帧,如下所示:

#  A  B  C  D
#  4  12 1  6
#  3  5  3  8
#  6  1  9  4
其中A、B、C、D是列名, 及

其中id和value是列名

我试图编写一个代码,将每列中的所有值除以第二个数据帧中的“值”。
我尝试在这里搜索,使用一些软件包,手工编写自己的循环,但没有任何效果。我的数据帧有数千列,所以我无法手动键入。请帮助并感谢您。

一个
dplyr
解决方案可以是:

df1 %>%
 rowwise() %>%
 mutate(across(everything())/df2$value)

      A      B      C     D
  <dbl>  <dbl>  <dbl> <dbl>
1   0.4 0.8    0.0833   0.3
2   0.3 0.333  0.25     0.4
3   0.6 0.0667 0.75     0.2
df1%>%
行()
变异(跨越(一切())/df2$value)
A、B、C、D
1   0.4 0.8    0.0833   0.3
2   0.3 0.333  0.25     0.4
3   0.6 0.0667 0.75     0.2
在baseR中,您可以

df1 / split(df2$value, names(df1))
#    A          B          C   D
#1 0.4 0.80000000 0.08333333 0.3
#2 0.3 0.33333333 0.25000000 0.4
#3 0.6 0.06666667 0.75000000 0.2

split(df2$value,names(df1))
返回按
names(df1)
排序的列表:

df1
然后按列除以该列表的值

数据

df1 <- structure(list(A = c(4L, 3L, 6L), B = c(12L, 5L, 1L), C = c(1L, 
3L, 9L), D = c(6L, 8L, 4L)), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(id = c("A", "B", "C", "D"), value = c(10L, 15L, 
12L, 20L)), class = "data.frame", row.names = c(NA, -4L))
df1 <- structure(list(A = c(4L, 3L, 6L), B = c(12L, 5L, 1L), C = c(1L, 
3L, 9L), D = c(6L, 8L, 4L)), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(id = c("A", "B", "C", "D"), value = c(10L, 15L, 
12L, 20L)), class = "data.frame", row.names = c(NA, -4L))

df1这里有一个带有
deframe

library(tibble)
df1/deframe(df2)[col(df1)]
#   A          B          C   D
#1 0.4 0.80000000 0.08333333 0.3
#2 0.3 0.33333333 0.25000000 0.4
#3 0.6 0.06666667 0.75000000 0.2
或者在
base R

df1/df2$value[match(df2$id, names(df1))][col(df1)]
数据
df1
df1/df2$value[match(df2$id, names(df1))][col(df1)]
df1 <- structure(list(A = c(4L, 3L, 6L), B = c(12L, 5L, 1L), C = c(1L, 
3L, 9L), D = c(6L, 8L, 4L)), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(id = c("A", "B", "C", "D"), value = c(10L, 15L, 
12L, 20L)), class = "data.frame", row.names = c(NA, -4L))