将所有值除以R studio中其行的最后一个条目
我在R studio工作,我有一个数据集,如: (字母代表列名) 我想将所有值除以对应于其列的f值。这意味着第一行中的每个值必须除以1,第二行中的每个值除以2,第三行中的每个值除以4 我试过这样做:将所有值除以R studio中其行的最后一个条目,r,R,我在R studio工作,我有一个数据集,如: (字母代表列名) 我想将所有值除以对应于其列的f值。这意味着第一行中的每个值必须除以1,第二行中的每个值除以2,第三行中的每个值除以4 我试过这样做: #divide every number through sum variable of their row my_matched_matrix = as.matrix(my_matched) #making a vector out of sum row avector <- as.vec
#divide every number through sum variable of their row
my_matched_matrix = as.matrix(my_matched)
#making a vector out of sum row
avector <- as.vector(my_matched['sum'])
#sweep
sweeped <- sweep(mat,avector, `/`)
有人知道有没有其他方法可以达到我想要的目的吗?这就是你想要的吗
df <- read.table(text = "a b c d e f
0 1 3 1 0 1
3 1 0 4 1 2
0 1 0 0 3 4",
header = TRUE, stringsAsFactors = FALSE
df / df$f
如果您想让它打印得更好,可以这样做:
x <- df / df$f
format(x, nsmall = 2)
a b c d e f
1 0.00 1.00 3.00 1.00 0.00 1.00
2 1.50 0.50 0.00 2.00 0.50 1.00
3 0.00 0.25 0.00 0.00 0.75 1.00
x如果f
是您的最后一列,并且数据集是对象df
,那么这应该可以工作:df[,1:(ncol(df)-1)]/df[,ncol(df)]
尝试df[,1:(ncol(df)-1]/df$f
df <- read.table(text = "a b c d e f
0 1 3 1 0 1
3 1 0 4 1 2
0 1 0 0 3 4",
header = TRUE, stringsAsFactors = FALSE
df / df$f
a b c d e f
1 0.0 1.00 3 1 0.00 1
2 1.5 0.50 0 2 0.50 1
3 0.0 0.25 0 0 0.75 1
x <- df / df$f
format(x, nsmall = 2)
a b c d e f
1 0.00 1.00 3.00 1.00 0.00 1.00
2 1.50 0.50 0.00 2.00 0.50 1.00
3 0.00 0.25 0.00 0.00 0.75 1.00