首页 \ 问答 \ 重新调整矢量R(Rescale Vector R)

重新调整矢量R(Rescale Vector R)

假设我有一个整数向量,例如:

> x
[1]  1  1  1  4  4 13 13 14

我在R中寻找一种有效的方法来将矢量重新调整为整数1,以将元素的唯一数量最大化。 因此得到的向量将是:

1 1 1 2 2 3 3 4

看起来像一个简单的问题,但我很难找到一个有效的方法来做到这一点。 在实践中,这个向量很大(大约500)。


Suppose I have a vector of integers such as:

> x
[1]  1  1  1  4  4 13 13 14

I am looking for an efficient way in R to rescale the vector to integers 1 to the max of the unique number of elements. Therefore the resulting vector would be:

1 1 1 2 2 3 3 4

Seems like a simple problem but I'm having trouble finding an efficient way to do it. In practice this vector is large (around 500).


原文:https://stackoverflow.com/questions/13434204
更新时间:2019-09-11 14:43

最满意答案

尝试match(x, sort(unique(x)))

x <- sample(1:50, 1e6, replace = TRUE)
benchmark(as.integer(factor(x)), match(x, sort(unique(x))),
          replications = 20, columns = c("test", "elapsed", "relative"))
#                        test elapsed relative
# 1     as.integer(factor(x))   18.44    10.36
# 2 match(x, sort(unique(x)))    1.78     1.00

identical(as.integer(factor(x)), match(x, sort(unique(x))))
# [1] TRUE

Try match(x, sort(unique(x))):

x <- sample(1:50, 1e6, replace = TRUE)
benchmark(as.integer(factor(x)), match(x, sort(unique(x))),
          replications = 20, columns = c("test", "elapsed", "relative"))
#                        test elapsed relative
# 1     as.integer(factor(x))   18.44    10.36
# 2 match(x, sort(unique(x)))    1.78     1.00

identical(as.integer(factor(x)), match(x, sort(unique(x))))
# [1] TRUE
2012-11-17

相关问答

更多

用R中的矢量着色条形图着色(Conditional Barchart coloring with a vector in R)

使用 barplot(x, ylim=c(-8,8), col=ifelse(x>0,"red","blue")) col=期望一个长度与x相同的向量(或者它将循环使用值)。 你不能真正有条件地指定这样的参数。 ifelse会根据需要制作矢量,而不像它只运行一次。 Use barplot(x, ylim=c(-8,8), col=ifelse(x>0,"red","blue")) col= expects a vector with the same length as x (or it w

在R中创建矢量精确副本的最简单方法是什么?(Simplest way to create an exact copy of a vector in R?)

正如Ken的回答和我的评论所指出的,我认为99%的R社区会建议你使用<-运算符。 但是,关于2个对象在内存中的位置的注释是正确的。 library(pryr) x <- c(1, 2, 3) y <- x pryr::address(x) == pryr::address(y) #true pryr::address(x) # [1] "0x5832a668" 现在,如果你修改其中一个会发生什么? x <- "hello world" x # [1] "hello world" # updat ...

为什么R中的转储函数没有创建文件?(Why is the dump function in R not creating a file?)

dump函数采用变量名称的矢量,而不是变量本身。 尝试 x<-"foo" y<-1 dump(c("x","y"),file="dump.R") list.files() The dump function takes a vector of names of variables, not the variables themselves. Try x<-"foo" y<-1 dump(c("x","y"),file="dump.R") list.files()

如何将字符串向量转换为R中的整数向量?(How to convert a vector of string into vector of integers in R?)

一种通用方法: as.numeric(gsub("\\D+", "", A)) #[1] 162 139 87 175 54 25 46 16650 16776 16689 16844 A generalized approach: as.numeric(gsub("\\D+", "", A)) #[1] 162 139 87 175 54 25 46 16650 16776 16689 16844

C矢量作为char ***矢量(C vector as char *** vector)

假设你想要一个创建字符串向量的函数。 您可以定义它并像这样调用它: #include "stdio.h" #include "stdlib.h" void make_vector(char*** vvar) { /* We're going to create a vector of strings. */ char** vector = malloc(sizeof(char*) * 3 ); vector[0] = "Hello"; vector[1] = "worl

如何将文本文件作为字符向量导入到R中(how to import a text file into R as a character vector)

用gsub删除gsub后尝试strsplit A <- strsplit(gsub('\\s+', '', lines),'')[[1]] A #[1] "H" "e" "l" "l" "o" "m" "y" "n" "a" "m" "e" "i" "s" "F" "a" "g" "u" "i" "C" #[20] "u" "r" "t" "a" "i" "n" 要么 library(stringi) stri_extract_all_regex(lines, '\\w')[[1]] #[1]

R:ifelse函数返回矢量位置而不是值(字符串)(R: ifelse function returns vector position instead of value (string))

现场answer是因子,因此您的函数返回数字(因子水平)。 你需要做的是: aDDs$answer <- as.character(aDDs$answer) 然后它工作。 The field answer is factor, hence your function returns number (level of factor). What you need to do is: aDDs$answer <- as.character(aDDs$answer) and then it work ...

矢量化数据帧的行,应用矢量函数,返回原始数据帧r(vectorise rows of a dataframe, apply vector function, return to original dataframe r)

似乎这只是一个简单的apply问题,你想cbind到df: > cbind(df, apply(df[ , 4:2] # work with columns in reverse order , 1, # do it row-by-row cummax) ) a b c d 1 2 3 d a 1 2 2 2 1 6 c b 2 3 1 2 3 6 b c 5 4 6 2 3 6 哎哟。 由于 ...

相关文章

更多

最新问答

更多
  • .net Rx:消息的有序批处理(.net Rx: in-order batch-processing of messages)
  • 查询在给定区域中包含全景图的商业场所的api?(Query places api for business venues in given area which contain panoramas?)
  • linux启动的时候的两条进度条各表示在加载什么?
  • 测试是否已存在某些内容(Testing if something already exists)
  • iOS7和jQuery mobile:面板在打开和关闭后变为空白(iOS7 and jQuery mobile: panel goes blank once opened and closed)
  • 在Spring中结合GET和POST请求方法(Combine GET and POST request methods in Spring)
  • 从Geany内部运行应用程序的多个实例(Run multiple instances of an application from inside Geany)
  • 使用Yii2在邮件中嵌入图像时出错(Error when embed image in mail using Yii2)
  • 带有不同频率的LED计数器程序(0 - 15)(Led Counter Program (0 - 15) with different frequencies)
  • Google支持SAML 2.0 ECP(Google support for SAML 2.0 ECP)
  • 如何识别结构构件的尺寸?(How can i identify the size of structure member?)
  • 带有计数器的列表迭代中的Netlogo列表(Netlogo list in list iterations with counter)
  • Eclipse CDT中对函数的未定义引用(undefined reference to function in Eclipse CDT)
  • 如何确定一个类是否是java中接口的实现(How to determine if a class which is an implemenation of an interface in java)
  • Wireshark捕获过滤器示例(Wireshark Capture Filter Example)
  • 什么是NoSQL?(What exactly is NoSQL?)
  • 如何在sass中编写媒体查询?(How to write media queries in sass?)
  • spring destroy-method +请求范围bean(spring destroy-method + request scope bean)
  • ssis包中全局表的范围(Scope of Global Table in ssis package)
  • 如何在较小的屏幕上禁用Bootstrap的“词缀”?(How can I disable Bootstrap's “affix” on smaller screens?)
  • SQLite Min函数在使用String数据的行中返回NULL(SQLite Min function returns NULL in row with String data)
  • 如何在Cordova中更新应用程序版本(How to update app version in Cordova)
  • 当我在while循环中使用char []读取Android中的文本文件时出现重复行(repeated lines when I use char[] in while loop for reading text file in Android)
  • 有没有办法按顺序打印数组,在[TCL]中输入条目(Is there a way to print array in order with entries entered in that [TCL])
  • 如何在倒排索引结构中搜索短语查询?(How to search phrase queries in inverted index structure?)
  • 导致在WCF中返回HTTP错误状态(Causing HTTP error status to be returned in WCF)
  • qsqltablemodel不兼容的数据类型(qsqltablemodel incompatible data types)
  • 如何在没有包的情况下引用Java文件?(How can I reference Java files without packages?)
  • Rails 4.1.1相关模型属性,嵌套表单不保存(Rails 4.1.1 related model attribute with nested form not saving)
  • 如何将byte []转换成字符串?(How to convert UTF-8 byte[] to string?)