如何使用as.numeric将随机数向量转换为0,1,2的向量?

时间:2016-11-22 14:49:45

标签: r

假设我有一个向量$(0,1,2,3,4,5)$。 我想将其转换为以下内容:如果原始向量中的值为:

$ = 0 \ rightarrow 0 $

$> 0 $但$< 5 \ rightarrow 1 $

$ = 5 \ rightarrow 2 $

我试过了:

    <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
   <connectionStrings>
    <add name="myConnectionString" providerName="Npgsql" connectionString="Host=localhost;Port=5432;Database=mv_test;User Id=postgres;Password=devel;" />
  </connectionStrings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

3 个答案:

答案 0 :(得分:5)

您可以使用两个逻辑操作并添加结果:

v <- c(0,1,2,3,4,5)
v <- as.numeric(v=0, v>0 & v<5, v=5)

答案 1 :(得分:3)

v2 <- (v > 0) + (v >= 5)
# [1] 0 1 1 1 1 2

答案 2 :(得分:1)

您也可以尝试:

> vs <- as.numeric(ifelse(v==0,0,ifelse(v>0 & v<5,1,2)))
> vs
[1] 0 1 1 1 1 2