首页 \ 问答 \ 在大多数列具有多个值的情况下,重新变换为宽到宽(Reshape long to wide where most columns have multiple values)

在大多数列具有多个值的情况下,重新变换为宽到宽(Reshape long to wide where most columns have multiple values)

我有以下数据:

IDnum   zipcode   City          County   State
10011   36006     Billingsley   Autauga  AL 
10011   36022     Deatsville    Autauga  AL
10011   36051     Marbury       Autauga  AL
10011   36051     Prattville    Autauga  AL
10011   36066     Prattville    Autauga  AL
10011   36067     Verbena       Autauga  AL
10011   36091     Selma         Autauga  AL
10011   36703     Jones         Autauga  AL
10011   36749     Plantersville Autauga  AL
10011   36758     Uriah         Autauga  AL
10011   36480     Atmore        Autauga  AL
10011   36502     Bon Secour    Autauga  AL

我有一个zipcodes列表,它们包含的城市,以及它们所在的县/州.IDnum =县和州的数值,合并。 列表是您现在看到的格式,我需要将其从长到宽/垂直到水平重新整形,其中IDnum变量成为唯一标识符,所有其他可能的值组合变为宽变量。

IDnum  zip1   city1        county1  state1  zip2   city2       county2
10011  36006  Billingsley  Autauga  AL      36022  Deatsville  Autauga

这只是数据集的示例,它包含了美国的每个zip,包含更多变量。 我已经看到了与此类似的其他问题和答案,但并不是几乎每列都有多个值的地方。

SPSS和STATA中的命令将以这种方式重塑数据,在SPSS中我可以运行Restructure / Cases to Vars命令,将我的初始数据集中的11个变量转换为大约1750,b / c一个县有超过290个拉链并且它重复大多数其他变量290+次。 这将创建许多空白,但我需要将它重新整形为一个非常长的水平文件。

我查看了reshape和reshape2,并挂断了'default to length'错误消息。 我确实得到了融合/ dcast以进行排序工作,但这会创建一个变量,它是所有值的列表,而不是为每个值创建变量。

melted_dupes <- melt(zip_code_list_dupes, id.vars= c("IDnum"))
HRZ_dupes <- dcast(melted_dupes, IDnum ~ variable, fun.aggregate = list) 

我尝试过tidyr和dplyr,但在语法上迷失了方向。 有点惊讶的是,没有命令数据类似于其他包中的内置命令,让我假设有,我只是没有想出来。

任何帮助表示赞赏。


I have data as below:

IDnum   zipcode   City          County   State
10011   36006     Billingsley   Autauga  AL 
10011   36022     Deatsville    Autauga  AL
10011   36051     Marbury       Autauga  AL
10011   36051     Prattville    Autauga  AL
10011   36066     Prattville    Autauga  AL
10011   36067     Verbena       Autauga  AL
10011   36091     Selma         Autauga  AL
10011   36703     Jones         Autauga  AL
10011   36749     Plantersville Autauga  AL
10011   36758     Uriah         Autauga  AL
10011   36480     Atmore        Autauga  AL
10011   36502     Bon Secour    Autauga  AL

I have a list of zipcodes, the cities they encompass, and counties/states they are located in. IDnum = numeric value for county and state, combined. List is in format you see now, I need to reshape it from long to wide / vertical to horizontal, where the IDnum variable becomes the unique identifier, and all other possible value combinations become wide variables.

IDnum  zip1   city1        county1  state1  zip2   city2       county2
10011  36006  Billingsley  Autauga  AL      36022  Deatsville  Autauga

This is just sample of the dataset, it encompasses every zip in the USA and includes more variables. I have seen other questions and answers similar to this one, but not where there are multiple values in almost every column.

There are commands in SPSS and STATA that will reshape data this way, in SPSS I can run a Restructure/Cases to Vars command that turns 11 variables in my initial dataset into about 1750, b/c one county has over 290 zips and it replicates most of the other variables 290+ times. This will create many blanks, but I need it to be reshaped into one very long horizontal file.

I have looked at reshape and reshape2, and am hung up on the 'default to length' error message. I did get melt/dcast to sorta work, but this creates one variable that is a list of all values, rather than creating variables for each value.

melted_dupes <- melt(zip_code_list_dupes, id.vars= c("IDnum"))
HRZ_dupes <- dcast(melted_dupes, IDnum ~ variable, fun.aggregate = list) 

I have tried tidyr and dplyr but got lost in syntax. Am a little surprised there isn't a command the data similar to built in commands in other packages, making me assume there is, and I just haven't figured it out.

Any help is appreciated.


原文:https://stackoverflow.com/questions/41982078
更新时间:2021-05-04 11:05

最满意答案

方法重写必须具有与其重写的父方法相同的方法签名 ,否则它不会被重写。

Java

public abstract class AbstractTest {

    public abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

正如你所看到的, ConcreteTest (它扩展了AbstractTest )必须覆盖test() 。 它们具有相同的方法名称,返回类型和方法参数。 子类可以省略从基类抛出的异常并抛出它自己的异常。 该子类还可以添加额外的(未)检查异常。

正如Peter Lawrey所提到的,java接口方法是隐式抽象方法(参见我在Java抽象接口上的问题 )。

这里至关重要的是,在这种情况下,方法可见性无法改变(因为它是一种层次可见性,即private-> protected-> public)。 虽然这是有效的:

public abstract class AbstractTest {

    protected abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

(父级拥有受保护的方法,子类可以覆盖相同的方法,并且只有2种可见性选择:受保护或公共权限)。

另外,假设你有

public class B {

}

public class D extends B {

}

public abstract class Base {

    public abstract B foo();
}

public class Derived extends Base {

    @Override
    public D foo() {
        // TODO Auto-generated method stub
        return new D();
    }

}

你会看到Derived返回一个D而不是B 这是为什么? 这是因为派生类遵循父类相同的签名 ,派生类的返回类型是父类的返回类型的子类型。

所以,我可以这样做:

Base pureBase = new Derived();
B b = pureBase.foo(); //which returns class D

if (b instanceof D) {
   //sure, it is, do some other logic
}

在C ++中,使用Covariant Return类型可以获得类似的效果

C ++

class AbstractTest {
public:
    virtual void test() = 0;
};


class ConcreteTest : AbstractTest {
public:
    void test() {
        //Implementation here...
    }
};

在C ++中,具有纯虚函数的类(以a =0结尾的虚函数)被称为Abstract类。 子类(在C ++中,类扩展由:分隔)覆盖纯虚方法(除了不包含=0 )。 它的父类具有相同的签名。

回到我们的Java示例,假设您有:

class B {

};

class D : B {

};

class Base {
public:
    virtual B* foo() = 0;
}

class Derived : Base {
public:
    D* foo() {
        return new D();
    }
}

在这里完成相同的推理(如java中所解释的)。 协变返回类型也适用于受保护和私有继承。 有关Covariant返回类型的更多信息。


Method overriding must have the same method signature of the parent method it's overriding, otherwise it's not called overriding.

Java:

public abstract class AbstractTest {

    public abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

As you can see, ConcreteTest (which extends AbstractTest) must override test(). They have the same method name, return types and no method parameters. The subclass can omit the exceptions thrown from the base class and throw its own Exception. The subclass can also add additional (un)checked exception.

As Peter Lawrey mentioned, a java interface methods are implicitly abstract method (See my SO question on Java Abstract Interface).

What is crucial here is that the method visibility cannot change in this case (as it's a hierarchical visibility, i.e. private->protected->public). This is valid though:

public abstract class AbstractTest {

    protected abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

(The parent has a protected method and the subclass can override the same method and only has 2 choice for visibility: protected or public).

Also, Suppose you have

public class B {

}

public class D extends B {

}

public abstract class Base {

    public abstract B foo();
}

public class Derived extends Base {

    @Override
    public D foo() {
        // TODO Auto-generated method stub
        return new D();
    }

}

You will see that Derived returns a D and not a B. Why is that? That's because the derived class follows the same signature as the parent class and the return type of the derived class is a subtype of the return type of the parent class.

So, I can have this:

Base pureBase = new Derived();
B b = pureBase.foo(); //which returns class D

if (b instanceof D) {
   //sure, it is, do some other logic
}

In C++, you can get similar effect, using Covariant Return types

C++

class AbstractTest {
public:
    virtual void test() = 0;
};


class ConcreteTest : AbstractTest {
public:
    void test() {
        //Implementation here...
    }
};

In C++, a class with a pure virtual function (a virtual function that ends with a =0) is known as an Abstract class. The subclass (in C++, class extension is delimited by :) override the pure virtual method (except it doesn't contain the =0). It has the same signature has its parent class.

Going back to our Java example, suppose you have:

class B {

};

class D : B {

};

class Base {
public:
    virtual B* foo() = 0;
}

class Derived : Base {
public:
    D* foo() {
        return new D();
    }
}

The same reasoning (as explained in java) is done here. Covariant return types also works with protected and private inheritance. More on Covariant return types.

相关问答

更多
  • C ++,C#,Objective-C和Java都可以调用C例程。 以下是一些链接,可以让您全面了解所询问的每种语言的C调用过程。 从Java调用C 从C ++调用C语言 从C#调用C 从Objective-C调用C. C++,C#, Objective-C, and Java can all call C routines. Here are a few links that will give you an overview of the process needed to call C from ea ...
  • 您仍然可以在继承C ++中的类时声明具有相同签名的非虚拟成员函数,因为Java显式禁止声明具有相同签名的方法,其中基类声明该方法为final。 在处理继承/多态性时,C ++中的虚拟性有助于找到正确的函数。 例: #include class Base { public: void doIt() { std::cout << "from Base.doIt()" << std::endl; } }; class Child : public ...
  • 不可以。您不能重写静态成员。 你的想法很好。 只需重构代码即可使用实例成员并覆盖它们。 或者更好的是,在他的特定情况下 - 将值作为构造函数参数传递。 您不是重写任何逻辑,只需要在字段中存储和返回数据。 No. You can not override static members. Your idea is good. Just Refactor the code to use instance members and override them. Or better yet, int his speci ...
  • 对cout和printf C ++调用不会显示在LogCat输出中。 有两种解决方案。 使用NDK提供的记录宏允许您将消息记录到LogCat。 这对于您正在编写的新代码和包装代码很有用,但是当您拥有一个充满现有调试语句的库时不太好。 我将宏定义如下: #define LOG_INFO(info) __android_log_write(ANDROID_LOG_INFO,"JNI",info) #define LOG_ERROR(error) __android_log_write(ANDROID_LOG_E ...
  • 首先,有一些工具(具有不同的质量和功能)可以将编译后的机器代码逆向转换回原始语言[或其他语言,就此而言]。 这样做的最大问题是像C和C ++这样的语言,结构中成员的名称没有名称,并且通常变得“平坦”,所以最初的原因是: struct user { std::string name; int age; int score; }; 会变成: struct s0 { char *f0; char *f1; int f2; int f3; ...
  • 不覆盖目标c中的方法没有实际的限制。 你可以像Dan Lister在他的回答中所建议的那样使用一个协议,但这只是强制执行你的符合类来实现在该协议中声明的某种行为。 目标c中的抽象类的解决方案可能是: interface MyClass { } - (id) init; - (id) init { [NSException raise:@"Invoked abstract method" format:@"Invoked abstract method"]; return nil; } ...
  • 通常,您要查找的是virtual关键字。 简而言之, virtual声明了可以覆盖此方法的意图。 请注意,这样的方法仍然可以具有实现 - virtual只是使其可重写。 要声明一个“抽象方法”,你可以说声明意图请在派生类中提供一个 = 0 ,如下所示。 这些方法在C ++中称为纯虚拟 。 但是,您应该注意一些警告。 正如下面的评论所指出的那样,你是在SuperClass构造函数中调用method() 。 不幸的是,由于构造对象的顺序,这在C ++中是不可能的。 在C ++中,派生类构造函数在分配其成员或执行 ...
  • 你猜对了,“多态”是关键词:)多态性意味着如果Y是X一个子类,那么Y实际上就是 X ,并且可以在任何地方用作X 现在,这意味着,如果X有一个方法void k() ,那么Y也必须有相同的方法(否则,你将无法将它用作X )。 但是你不能有两个具有相同签名的不同方法,因此Yk()也必须返回void (否则,它将是一个不同的方法)。 在C ++的情况下,非虚函数不是多态的:在这种情况下, Ak和Bk是两种完全不同的方法,因此没有限制。 简而言之,让我们稍微改变你的例子:假设你定义了Xk返回int ,而Yk()为vo ...
  • 我可以建议两种选择: 只需使用boost::recursive_mutex (或者在C ++ 11中使用std::recursive_mutex )。 (更好)始终从同步代码调用非同步私有实现: class Test { private: mutex obj; public: void fn1() { unique_lock lock(obj); fn1Helper(); } void fn2(bool calledFromWith ...
  • 方法重写必须具有与其重写的父方法相同的方法签名 ,否则它不会被重写。 Java : public abstract class AbstractTest { public abstract void test() throws Exception; } public class ConcreteTest extends AbstractTest { @Override public void test() throws Exception { } } 正如你所看到的 ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)