r - 如何重新缩放数据框,使每行在 R 中的大小为 1?
问题描述
这是我的矩阵和代码的示例。我想重新调整我的数据框,使每一行的大小为 1。我是 r 的新手,在教程中,讲师说“将行的每个元素除以行的大小”。但是我不确定如何获得行的大小或重新调整数据帧。所以我尝试使用apply()但是在使用sqrt(sum(sc_mydata[r,]^2))测试我的重新缩放后我没有得到 1,我 x 的结果应该是 1
#dataframe
myData <- myData[1:12]
#transpose
x <- t(myData)
#rescale the data
sc_mydata = apply(x[-1,], 1, scale)
#test rescale
for (r in 1:nrow(sc_mydata)) {
#test rescale if this is equal to 1 then the rescaling worked
x <- sqrt(sum(sc_mydata[r,]^2))
}
atr1 atr2 atr3 atr4 atr5 atr6 atr7 atr8 atr9 atr10 atr11 atr12
1 -0.35975 -0.42125 -0.33200 -0.08900 -0.16175 -0.44275 -0.38925 0.02975 -0.68525 -0.27500
2 0.01950 -0.27875 -0.18450 -0.30775 -0.34625 0.00200 -0.12425 -0.29475 -0.35375 -0.09575 -0.39150 0.00225
3 0.08350 -0.23125 -0.28025 -0.28975 -0.37325 0.01525 -0.11725 -0.29775 -0.32325 -0.09500 -0.55850 -0.11700
4 0.02225 -0.23675 -0.22425 -0.33925 -0.37075 -0.00375 -0.18450 -0.29250 -0.38450 -0.00400 -0.38975 -0.13850
5 0.05125 -0.35400 -0.31425 -0.35700 -0.26650 -0.07725 -0.11275 -0.34125 -0.30575 0.00550 -0.57025 -0.20600
6 0.01650 -0.28350 -0.10775 -0.29775 -0.16250 -0.03675 -0.1360
解决方案
If by "the magnitude of the row" your instructor means "the sum of the row", this works:
sc_mydata <- apply(x, 1, function(x) x / sum(x, na.rm = TRUE))
sc_mydata <- t(sc_mydata)
For some reason, the row-wise apply()
function transposes the data frame, so I had to transpose it back. I don't use apply much (prefer the tidyverse
tools to base R) so idk why that happens.
推荐阅读
- vbscript - 如何在 vbScript 中打乱函数的名称
- python - Python烧瓶TypeError:'int'对象不可迭代
- api - 微服务中的 OAuth 2.0:当一个资源服务器与另一个资源服务器通信时
- performance - 使用 UnboxedSums 定义的总和类型是否比普通枚举更有效?
- javascript - JSON 扩展而不覆盖具有相同名称的属性
- mysql - 如何在同一个 MySQL 命令中将日期字段格式化为不同的语言?
- php - PHP中基于键值循环遍历三个独立的std类对象数组
- ios - 如何以编程方式设置滚动视图高度
- c# - ASP.Net Identity 内置函数与 ASP.Net Core 中的自定义表
- html - 发出占位符自动建议